【问题标题】:Woocommerce change quantity min limit for each product in cartWoocommerce 更改购物车中每个产品的最小数量限制
【发布时间】:2017-08-14 08:39:53
【问题描述】:

我有一些产品只有在最小数量超过一定数量时才能购买。

我在我的子主题 functions.php 中编写并放置了一段代码,以更改产品的最小数量。

function wpa116693_filter_min_quantity( $min, $product ){

    if ( has_term ( '5', 'product_tag' ) ){
        return 5;
    }

    if ( has_term ( '10', 'product_tag' ) ){
        return 10;
    }

    if ( has_term ( '6', 'product_tag' ) ){
        return 6;
    }
}
add_filter( 'woocommerce_quantity_input_min', 'wpa116693_filter_min_quantity', 10, 2 );

所以它的作用是,如果它找到标签为 5 的产品,那么它会将数量 min 更改为 5。这在单个产品页面中有效,但在购物车页面中无效。我可以低于购物车页面中的最小数量。我认为它不起作用,因为“has_term”在购物车页面中不起作用。

我希望它也可以在购物车页面中使用。 请帮我解决这个问题,谢谢。

【问题讨论】:

    标签: php wordpress woocommerce cart hook-woocommerce


    【解决方案1】:

    您需要像这样将您的函数挂钩到woocommerce_cart_loaded_from_session

    add_action('woocommerce_cart_loaded_from_session', 'wh_checkAndUpdateCart');
    
    function wh_checkAndUpdateCart()
    {
    
        //if the cart is empty do nothing
        if (WC()->cart->get_cart_contents_count() == 0)
        {
            return;
        }
    
        foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item)
        {
            $product_id = $cart_item['product_id']; // Product ID
            $product_qty = $cart_item['quantity']; // Product quantity
    
            if (has_term(5, 'product_tag', $product_id) && ($product_qty > 5))
            {
                WC()->cart->set_quantity($cart_item_key, 5);
            }
            if (has_term(10, 'product_tag', $product_id) && ($product_qty > 10))
            {
                WC()->cart->set_quantity($cart_item_key, 10);
            }
            if (has_term(6, 'product_tag', $product_id) && ($product_qty > 6))
            {
                WC()->cart->set_quantity($cart_item_key, 6);
            }
        }
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件中。或者也可以在任何插件 php 文件中。
    代码已经过测试并且可以工作。

    希望这会有所帮助!

    【讨论】:

    • 嘿,它有效!!我想你误解了我一点,只是一点点。我将 if 运算符从“>”更改为“
    • 对不起,我没让你知道:可以为通过这个输入的数量添加一个 min 属性 -- 你想为此显示购物车错误消息吗?对于您的第二个问题,您需要使用您编写的代码发布一个新问题。
    • 数量输入有属性min和max。我想在您的代码中挂钩 min 属性代码,以便人们无法在输入框中输入低于最小数量的值。我在我的问题上发布的代码适用于单个产品页面。我有点解决了第二个问题,尝试将“add_action”更改为“add_filter”,它开始工作没有任何问题。也许您有不同的解决方案?
    • 您拥有product_id,因此您获得了最小最大值并进行检查,如果任何检查失败,则抛出类似wc_add_notice( __( 'You can not do that', 'textdomain' ), 'error' );的错误
    猜你喜欢
    • 2021-10-28
    • 2018-02-10
    • 2021-10-31
    • 2018-07-31
    • 2019-09-18
    • 2021-07-19
    • 2017-04-06
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多