【问题标题】:Allow add to cart 3 products max for a specific product category in Woocommerce允许将 Woocommerce 中特定产品类别的最多 3 个产品添加到购物车
【发布时间】:2018-08-07 11:46:22
【问题描述】:

我正在尝试通过免费送货向客户发送最多 3 个免费样品。

我创建了一些价格为 0 的产品并将它们设置在“样品”产品类别中。

此特定产品具有“单独销售”选项,因此客户只能拥有一个样品。

我不知道如何在购物车中最多只允许此产品类别中的 3 个样品产品。

感谢任何帮助。

【问题讨论】:

    标签: php wordpress woocommerce categories product


    【解决方案1】:

    这可以很容易地使用woocommerce_add_to_cart_validation 操作钩子将客户限制为“样本”产品类别中的最多 3 件商品,这样:

    add_action('woocommerce_add_to_cart_validation', 'max_3_items_for_samples', 20, 3 );
    function max_3_items_for_samples( $passed, $product_id, $quantity ) {
        // HERE define your product category ID, slug or name.
        $category = 'clothing';
        $limit = 3; // HERE set your limit
        $count = 0;
    
        // Loop through cart items checking for specific product categories
        foreach ( WC()->cart->get_cart() as $cat_item ) {
            if( has_term( $category, 'product_cat', $cat_item['product_id'] ) )
                $count++;
        }
        if( has_term( $category, 'product_cat', $product_id ) && $count == $limit )
            $count++;
    
        // Total item count for the defined product category is more than 3
        if( $count > $limit ){
            // HERE set the text for the custom notice
            $notice = __('Sorry, you can not add to cart more than 3 free samples.', 'woocommerce');
            // Display a custom notice
            wc_add_notice( $notice, 'error' );
            // Avoid adding to cart
            $passed = false;
        }
    
        return $passed;
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件中。

    经过测试并且有效。

    【讨论】:

    • 我也在寻找类似的完整商店解决方案,只允许将一个数量添加到购物篮中,但如果类别是“游戏”,则允许多个数量。
    【解决方案2】:

    上述解决方案不起作用。 1)它允许您在第一次添加产品时初始添加超过限制。我相信这是因为验证是在将商品添加到购物车之前进行的,但是上面的函数会循环遍历购物车中已经存在的商品,并且 2)它允许用户在/cart/ 页面,因为未使用 woocommerce_update_cart_validation 过滤器。

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2019-09-18
      相关资源
      最近更新 更多