php-根据Woocommerce中产品类别添加到购物车的最大商品数量

我正在尝试自定义商店,以便名为“ 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;
}

有人可以指出我在这里做错了什么以及如何获得期望的结果.

解决方法:

我稍微重新审视了您的代码,它正在工作.请尝试以下方法:

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文件中.

经过测试和工作.

上一篇:php-在WooCommerce存档页面的产品标题下添加简短描述


下一篇:php-从产品变体标题中删除属性值,并在单独的行上显示它们