Max item quantity added to cart based on product category in Woocommerce

久未见 提交于 2019-12-10 18:25:46

问题


I am trying to customize the shop such that Category named Quantity4 allows only 4 items to be added in the cart and category named Quantity6 allows only items to be added in the cart.

As far as I can get, this can be achieved using nested if statements, but somehow this doesn't work.

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

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

$cart_items_count = WC()->cart->get_cart_contents_count();
$total_count = $cart_items_count + $quantity;

if(has_term('quantity4','product_cat',$product_id )){
if($cart_items_count >= 4 || $total_count > 4){
        // Set to false
        $passed = false;
        // Display a message
        wc_add_notice( __( "You Chose a Box of 4 Items, Can't Add More", "woocommerce" ), "error" );
    }
  }

  else if (has_term('quantity6','product_cat',$product_id )){
    if($cart_items_count >= 6 || $total_count > 6){
        // Set to false
        $passed = false;
        // Display a message
        wc_add_notice( __( "You Chose a Box of 6 Items, Can't Add More", "woocommerce" ), "error" );
    }
}

return $passed;
}

Can someone pls point out what am I doing wrong here and how to get the desired results.


回答1:


I have revisited your code a bit and it's working. Please try this:

add_filter( 'woocommerce_add_to_cart_validation', 'only_four_items_allowed_add_to_cart', 10, 3 );
function only_four_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {
    $cart_count = WC()->cart->get_cart_contents_count();
    $total_count = $cart_count + $quantity;

    if ( has_term( 'quantity4','product_cat',$product_id ) && ( $cart_count >= 4 || $total_count > 4 ) ) {
        $passed = false; // Set to false
        $notice = __( "You Chose a Box of 4 Items, Can't Add More", "woocommerce" ); // Notice to display
    }
    elseif ( has_term( 'quantity6','product_cat',$product_id ) && ( $cart_count >= 6 || $total_count > 6 ) ) {
        $passed = false; // Set to false
        $notice = __( "You Chose a Box of 6 Items, Can't Add More", "woocommerce" ); // Notice to display
    }
    if( ! $passed )
        wc_add_notice( $notice, 'error' );

    return $passed;
}

Code goes in function.php file of your active child theme (or active theme).

Tested and works.



来源:https://stackoverflow.com/questions/48452739/max-item-quantity-added-to-cart-based-on-product-category-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!