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 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败