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

产品未在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;
  • 写回答

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;
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程