如何在不打破每个产品限制的情况下更新购物车中产品的固定数量?

问题描述 投票:0回答:1

我有这样一段代码,允许我通过下拉选项添加固定数量到我的购物车。我需要的是,每当我选择并添加一个数量到购物车中,它就会自动更新购物车中的数值,而不是增加更多的数量,导致每个产品的数量超限。

我可以限制购物车的总数量,但如果我可以限制每个产品的数量,也许问题就解决了?

有什么建议可以让我解决这个问题吗?

function woocommerce_quantity_input($data = null) {
    global $product;

    $defaults = array(
        'input_name' => array_key_exists('input_name', $data) ? $data['input_name'] : 'quantity',
        'input_value'   => '25',
        'style'     => apply_filters( 'woocommerce_quantity_style', 'float:left; margin-right:10px;', $product )
    );

    $lista = array(25, 50, 100, 250);

    $options = '';

    for ( $count = 0; $count < sizeof($lista); $count++) { 
        $valor = $lista[$count];
        $selected = ($valor === $data['input_value']) ? ' selected' : '';
        $options .= '<option value="' . $valor . '"'.$selected.'>' . $valor . ''; }

    echo '<div class="quantity_select" style="' . $defaults['style'] . '"><select name="' . esc_attr( $defaults['input_name'] ) . '" title="' . _x( 'Qty', 'Product quantity input tooltip', 'woocommerce' ) . '" class="qty">' . $options . '</select></div>';
}
wordpress woocommerce hook-woocommerce
1个回答
1
投票

经过一些研究和一些用户代码的帮助,在stackoverflow,我已经达到了这一点,这段代码和上面的代码的组合,结果在实现解决我的问题。我可以设置固定的数量,而不超过我定义的每个产品的限制。所以,在不突破限制的情况下,递增某个产品的固定数量的问题就解决了。

add_filter( 'woocommerce_add_to_cart_validation', 'control_limit_add_to_cart', 10, 3 );

function control_limit_add_to_cart( $passed, $product_id, $quantity ) {

    //set max quantity per product in cart
    $max_per_product_qty = 250;
    //variable for over quantity verfication
    $over_qty = false;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        //Get each product id and respective quantity
        $product_identity = $cart_item['data']->get_id();
        $product_quantity = $cart_item['quantity'];
        //Set variable with the requested quantity of some product plus the actual quantity already in cart of that same product 
        $total_quantity_request = $product_quantity + $quantity;

        //compare the quantity of some product in cart to the requested quantity value of that same product
        if( ( $product_identity == $product_id ) && ( ( $product_quantity > $max_per_product_qty ) || ( $total_quantity_request > $max_per_product_qty ) ) ){
            //variable with the name of the product requested
            $product_name = $cart_item['data']->get_name();
            //set variable with true verification for over quantity
            $over_qty = true;
        }
    }

    if( $over_qty ){
        // Result is false==error
        $passed = false;
        // Write msg
         wc_add_notice( __( "You've the amount limit for the product ".$product_name.".", "woocommerce" ), "error" );
    }
    return $passed;
}
© www.soinside.com 2019 - 2024. All rights reserved.