【问题标题】:Allow add to cart for specific products based on cart total in WooCommerce允许根据 WooCommerce 中的购物车总数将特定产品添加到购物车
【发布时间】:2018-07-23 00:13:45
【问题描述】:

在 woocommerce 中,我试图找到一种方法,仅在达到特定购物车总金额时才允许将产品添加到购物车中。

示例:我们想以 $1 的价格出售保险杠贴纸,但前提是用户已经拥有价值 $25 的其他产品购物车。这类似于亚马逊的“附加”功能。但是我找不到类似的 WooCommerce 插件或功能。

我已经尝试了一些代码但没有成功...任何帮助将不胜感激。

【问题讨论】:

    标签: php wordpress woocommerce cart product


    【解决方案1】:

    可以使用挂在woocommerce_add_to_cart_validation 过滤器挂钩中的自定义函数来完成,您将在其中定义:

    • 一个产品 ID(或多个产品 ID)。
    • 要达到的阈值购物车数量。

    在达到特定购物车数量之前,将避免将那些定义的产品添加到购物车(显示自定义通知)。

    代码:

    add_filter( 'woocommerce_add_to_cart_validation', 'wc_add_on_feature', 20, 3 );
    function wc_add_on_feature( $passed, $product_id, $quantity ) {
    
        // HERE define one or many products IDs in this array
        $products_ids = array( 37, 27 );
    
        // HERE define the minimal cart amount that need to be reached
        $amount_threshold = 25;
    
        // Total amount of items in the cart after discounts
        $cart_amount = WC()->cart->get_cart_contents_total();
    
        // The condition
        if( $cart_amount < $amount_threshold && in_array( $product_id, $products_ids ) ){
            $passed = false;
            $text_notice = __( "Cart amount need to be up to $25 in order to add this product", "woocommerce" );
            wc_add_notice( $text_notice, 'error' );
        }
        return $passed;
    }
    

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

    经过测试并且有效。

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2020-04-28
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 2021-08-22
      • 2011-12-19
      • 1970-01-01
      • 2019-10-02
      相关资源
      最近更新 更多