有条件地限制为来自特定产品子类别的 1 个购物车项目
Conditionally limit to 1 cart item from a particular product subcategory
我找到了这个限制只能购买一种产品的代码,但我想知道是否可以更改它,以便客户只能购买某个子类别中的一种产品。
代码:
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
return $cart_item_data;
}
因此,如果客户将此特定产品子类别中的新产品添加到购物车,它将检查购物车中是否已有此产品子类别中的项目,如果是,则将其删除,保留新添加的产品.
我怎样才能做到这一点?
谢谢。
已更新 (2018 年 10 月)
代码中使用的挂钩 woocommerce_add_cart_item_data
和 $woocommerce->cart->empty_cart();
将完全清空所有购物车项目,不适合您的要求。此外,此代码有些陈旧。
要获得所需内容,请尝试使用此代码(您必须设置子类别 slug 才能使其正常工作):
add_action( 'woocommerce_before_calculate_totals', 'one_subcategory_cart_item', 10, 1 );
function one_subcategory_cart_item( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Set HERE your subcategory (can be an ID, a slug or the name)
$subcategory = 't-shirts';
$count_subcategory = 0;
// First cart loop: Counting number of subactegory items in cart
foreach ( $cart->get_cart() as $cart_item )
if( has_term( $subcategory, 'product_cat', $cart_item['product_id'] ) )
$count_subcategory++;
// Second cart loop: Removing subcategory items if more than one (keeping the last one)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if( $count_subcategory > 1 ) {
$cart->remove_cart_item( $cart_item_key );
break;
}
}
}
此代码已经过测试且功能齐全。
代码进入您的活动子主题(或主题)的 function.php 文件。或者在任何插件 php 文件中。
我找到了这个限制只能购买一种产品的代码,但我想知道是否可以更改它,以便客户只能购买某个子类别中的一种产品。
代码:
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
return $cart_item_data;
}
因此,如果客户将此特定产品子类别中的新产品添加到购物车,它将检查购物车中是否已有此产品子类别中的项目,如果是,则将其删除,保留新添加的产品.
我怎样才能做到这一点?
谢谢。
已更新 (2018 年 10 月)
代码中使用的挂钩 woocommerce_add_cart_item_data
和 $woocommerce->cart->empty_cart();
将完全清空所有购物车项目,不适合您的要求。此外,此代码有些陈旧。
要获得所需内容,请尝试使用此代码(您必须设置子类别 slug 才能使其正常工作):
add_action( 'woocommerce_before_calculate_totals', 'one_subcategory_cart_item', 10, 1 );
function one_subcategory_cart_item( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Set HERE your subcategory (can be an ID, a slug or the name)
$subcategory = 't-shirts';
$count_subcategory = 0;
// First cart loop: Counting number of subactegory items in cart
foreach ( $cart->get_cart() as $cart_item )
if( has_term( $subcategory, 'product_cat', $cart_item['product_id'] ) )
$count_subcategory++;
// Second cart loop: Removing subcategory items if more than one (keeping the last one)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if( $count_subcategory > 1 ) {
$cart->remove_cart_item( $cart_item_key );
break;
}
}
}
此代码已经过测试且功能齐全。
代码进入您的活动子主题(或主题)的 function.php 文件。或者在任何插件 php 文件中。