首页 > 解决方案 > 购物车更新后 WooCommerce 购物车数量不会改变

问题描述

我使用以下代码段来更改 WooCommerce 添加到购物车数量规则。

add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 10, 2 );

function custom_quantity_input_args( $args, $product ) {
$custom_qty_product_ids = array(27345, 27346);
if (!in_array($product->get_id(), $custom_qty_product_ids)) {
    $args['input_value']    = 25;

$args['max_value']  = 500;
$args['min_value']  = 25;
$args['step']       = 25;
} else {
    if (in_array($product->get_id(), $custom_qty_product_ids)){
        $args['input_value']    = 26;

$args['max_value']  = 260;
$args['min_value']  = 26;
$args['step']     = 26;
    }
}
return $args;
}

它适用于我的产品页面,但购物车更新后购物车数量不会改变,这是截图示例。

wc-cart-example-screenshot

以下片段(原始代码片段)完美运行,但我想将另一个规则应用于产品 27345、27346。

add_filter('woocommerce_quantity_input_args', 'c_qty_input_args', 10, 2);

function c_qty_input_args($args, $product) {
if(is_singular('product')) {
    $args['input_value'] = 25;
}
    $args['max_value']  = 500;
    $args['min_value']  = 25;
    $args['step']       = 25;

return $args;
}

如何更改代码段并解决问题?

谢谢!

标签: phpwordpresswoocommercecartproduct-quantity

解决方案


要使其适用于基于特定产品的不同设置,请尝试以下操作:

// General quantity settings
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 10, 2 );
function custom_quantity_input_args( $args, $product ){
    $product_ids = array(27345, 27346);
    $condition   = in_array( $product->get_id(), $product_ids );

    if( ! is_cart() ) {
        $args['input_value'] = $condition ? 25 : 26; // Starting value
    }

    $args['min_value'] = $condition ? 25 : 26; // Minimum value
    $args['max_value'] = $condition ? 500 : 260; // Maximum value
    $args['step']      = $condition ? 25 : 26; // Step value

    return $args;
}

// For Ajax add to cart button (define the min and max value)
add_filter( 'woocommerce_loop_add_to_cart_args', 'custom_loop_add_to_cart_quantity_arg', 10, 2 );
function custom_loop_add_to_cart_quantity_arg( $args, $product ) {
    $product_ids = array(27345, 27346);
    $condition   = in_array( $product->get_id(), $product_ids );
    
    $args['quantity'] = $condition ? 25 : 26; // Min value

    return $args;
}

// For product variations (define the min value)
add_filter( 'woocommerce_available_variation', 'custom_available_variation_min_qty', 10, 3);
function custom_available_variation_min_qty( $data, $product, $variation ) {
    $product_ids = array(27345, 27346);
    $condition   = in_array( $product->get_id(), $product_ids );
    
    $args['min_qty'] = $condition ? 25 : 26; // Min value
    $args['max_qty'] = $condition ? 500 : 260; // Max value

    return $data;
}

代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。


推荐阅读