donglizhan7848
2015-10-28 13:27
浏览 75
已采纳

产品未在woocommerce_add_to_cart_validation上的add_filter()之后添加到购物车中

I have a scenario in which a non logged user can only add 1 product in his cart. I am adding a filter on woocommerce_add_to_cart_validation which works fine with $woocommerce->cart->cart_contents_count>0 i.e. it displays a notice You cannot add another product to your cart.0 however, if I do $woocommerce->cart->cart_contents_count>1 the page just refresh without adding anything into cart. Below is my custom function for doing that.

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;

图片转代码服务由CSDN问答提供 功能建议

我有一个场景,其中非登录用户只能在他的购物车中添加1个产品。 我在 woocommerce_add_to_cart_validation 上添加了一个过滤器,它适用于 $ woocommerce-> cart-> cart_contents_count> 0 即显示通知您无法添加其他产品 到你的购物车。但是,如果我 $ woocommerce-> cart-> cart_contents_count> 1 ,页面只需刷新而不会在购物车中添加任何内容。 Below是我的自定义函数。

  if(!is_user_logged_in()):
add_filter('woocommerce_add_to_cart_validation','woocommerce_add_cart_myfunction'); 
 
function woocommerce_add_cart_myfunction(  $ cart_item_data){
 
全球$ woocommerce; 
 
 $ numberOfProducts = $ woocommerce-> cart-> cart_contents_count; 
 if($ numberOfProducts> 1){
 wc_add_notice(
 __(' 你无法在你的购物车中添加其他产品。'。$ numberOfProducts,'woocommerce')); 
返回false; 
} 
 
} 
endif; 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanlan4801 2015-10-28 13:31
    已采纳

    You need to return the cart item data, if the number of products is only 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;
    
    }
    
    打赏 评论

相关推荐 更多相似问题