douzhaiya3968 2017-03-22 09:56
浏览 89
已采纳

Woocommerce改变购物车中每件商品的最低限额

I have couple of products that can only be bought if min quantity is over certain number.

I wrote and put a snippet of code in my child themes functions.php to change the min quantity for products.

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 );

So what it does is, if it finds a product with the tag 5 then it will change the quantity min to 5. this works in single product page but it doesn't work in cart page. I can go lower than the min quantity in the cart page. I believe it doesn't work because "has_term" does not work in the cart page.

I want it to work in cart page too. Please help me solve this, thank you.

  • 写回答

1条回答 默认 最新

  • dounayan3643 2017-03-22 11:21
    关注

    You need to hook your function to woocommerce_cart_loaded_from_session like this:

    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);
            }
        }
    }
    

    Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
    Code is tested and works.

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多