【问题标题】:Product not adding in cart after add_filter() on woocommerce_add_to_cart_validationwoocommerce_add_to_cart_validation 上的 add_filter() 后产品未添加到购物车
【发布时间】:2015-10-28 13:27:20
【问题描述】:

我有一个场景,未登录的用户只能在他的购物车中添加 1 个产品。我在woocommerce_add_to_cart_validation 上添加了一个过滤器,它与$woocommerce->cart->cart_contents_count>0 一起工作正常,即它显示一个通知You cannot add another product to your cart.0 但是,如果我这样做$woocommerce->cart->cart_contents_count>1 页面只是刷新而不在购物车中添加任何东西。 下面是我的自定义函数。

if(!is_user_logged_in()):
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_cart_myfunction' );

function woocommerce_add_cart_myfunction( $cart_item_data ) {

    global $woocommerce;

$numberOfProducts=$woocommerce->cart->cart_contents_count;
    if($numberOfProducts > 1){
         wc_add_notice(
                     __( 'You cannot add another product to your cart.'.$numberOfProducts, 'woocommerce' ));
                return false;
    } 

}
endif;

【问题讨论】:

    标签: php wordpress woocommerce checkout cart


    【解决方案1】:

    如果商品数量只有1件,则需要返回购物车商品数据:

    function woocommerce_add_cart_myfunction( $cart_item_data ) {
    
        $numberOfProducts = WC()->cart->cart_contents_count;
        if ( $numberOfProducts > 1 ) {
             wc_add_notice(
                         __( 'You cannot add another product to your cart.'.$numberOfProducts, 'woocommerce' ));
             return false;
        }
    
        return $cart_item_data;
    
    }
    

    【讨论】:

    • 是的,我用$numberOfProducts < 2 && $numberOfProducts!=0 逻辑完成了这个,因为$numberOfProducts>1 实际上允许在购物车中添加2 产品
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2012-06-09
    相关资源
    最近更新 更多