【问题标题】:WooCommerce Another Way To Limit Maximum Cart ItemsWooCommerce 另一种限制购物车物品数量的方法
【发布时间】:2020-04-09 19:08:18
【问题描述】:
我想将用户可以在购物车中拥有的商品数量限制为最多 1 件商品(无论数量如何)。
关于如何使用 'woocommerce_add_to_cart_validation' 和 'woocommerce_update_cart_validation' 过滤器(例如 answer 1、answer 2、answer 3、...),有几个答案。
也可以使用现有的插件,例如this one,但它不支持最大项目数限制。
但是,就我而言,两个过滤器都没有触发,因为我正在使用的主题对“添加到购物车”逻辑进行了自定义(出于与此处讨论无关的业务/技术原因)。
也就是说,我需要使用不同的解决方案(使用其他过滤器,...)来实现相同的功能。
【问题讨论】:
标签:
php
wordpress
woocommerce
hook-woocommerce
【解决方案1】:
要实现所需的功能,可以使用 'woocommerce_add_cart_item' 过滤器来完成,如下所示:
add_filter( 'woocommerce_add_cart_item' , 'validate_cart_max_items');
function validate_cart_max_items( $item_data ) {
// Check total cart quantity
$cart_contents_count = WC()->cart->get_cart_contents_count();
// If quantity > 0, cancel current item addition to cart & display an error message
if($cart_contents_count > 0) {
$item_data = NULL;
wc_add_notice( "A maximum of 1 item can be added to your cart", "error" );
}
return $item_data;
}
上面的代码 sn-p 应该添加到你的活动主题文件夹下的 functions.php 文件中。
此代码 sn-p 已使用 WordPress v5.3.1 和 WooCommerce v3.8.1 进行了测试