doucaishou0074 2018-03-07 09:12
浏览 229
已采纳

在WooCommerce购物车页面中哪个Hook可以改变数量更新?

I'm trying to fire a function when the quantity of a product is changed in cart. More specifically I want to run this function when a customer modify the amount in a cart.

I'm looking to find the amount left in a cart then to intercept the update cart event

Currently I'm using:

add_action( 'woocommerce_remove_cart_item', 'my function');

When I press "update_cart", it doesn't seem to work. Any advice? Thank you!

  • 写回答

2条回答 默认 最新

  • duanluanhui8348 2018-03-07 09:30
    关注

    You should use woocommerce_after_cart_item_quantity_update action hook that has 4 arguments. But when quantity is changed to zero, woocommerce_before_cart_item_quantity_zero action hook need to be used instead (and has 2 arguments).

    Below is a working example that will limit the updated quantity to a certain amount and will display a custom notice:

    add_action( 'woocommerce_after_cart_item_quantity_update', 'limit_cart_item_quantity', 20, 4 );
    function limit_cart_item_quantity( $cart_item_key, $quantity, $old_quantity, $cart ){
        if( ! is_cart() ) return; // Only on cart page
    
        // Here the quantity limit
        $limit = 5;
    
        if( $quantity > $limit ){
            // Change the quantity to the limit allowed
            $cart->cart_contents[ $cart_item_key ]['quantity'] = $limit;
            // Add a custom notice
            wc_add_notice( __('Quantity limit reached for this item'), 'notice' );
        }
    }
    

    This code goes on function.php file of your active child theme (or theme). Tested and works.

    As this hook is located in WC_Cart set_quantity() method, is not possible to use that method inside the hook, as it will throw an error.


    To trigger some action when quantity is set to Zero use:

    add_action( 'woocommerce_before_cart_item_quantity_zero', 'action_before_cart_item_quantity_zero', 20, 4 );
    function action_before_cart_item_quantity_zero( $cart_item_key, $cart ){
        // Your code goes here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题