根据Woocommerce中产品类别添加到购物车的最大商品数量 [英] Max item quantity added to cart based on product category in Woocommerce

查看:48
本文介绍了根据Woocommerce中产品类别添加到购物车的最大商品数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自定义商店,以便名为 Quantity4的类别仅允许在购物车中添加4个项目,而名为 Quantity6的类别仅允许在购物车中添加项目。

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.

据我所知,可以使用嵌套的 if 语句来实现,但这在某种程度上是行不通的。

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.

推荐答案

我稍微重新浏览了一下您的代码,它可以正常工作。请尝试以下操作:

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;
}

代码进入活动子主题(或活动主题)的function.php文件)。

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

经测试可正常工作。

这篇关于根据Woocommerce中产品类别添加到购物车的最大商品数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆