我正在尝试自定义商店,以便名为Quantity4的类别只允许在购物车中添加4个商品,名为Quantity6的类别只允许在购物车中添加商品。
据我所知,这可以使用嵌套的if
语句来实现,但不知何故,这不起作用。
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;
}
有人可以指出我在这里做错了什么,以及如何获得理想的结果。
答案 0 :(得分:3)
我重新访问了你的代码并且它正在运行。请试试这个:
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文件中。
经过测试和工作。