doucaishou0074 2018-03-07 01: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 01: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 51单片机最小开发板系统,想让寻迹小车在全检测到黑线(寻迹模块代码在第一块板子上)时蜂鸣器响(在第二块板子上)
  • ¥15 pbootcms多选调用成列表
  • ¥15 51单片机oled显示时钟
  • ¥15 小规模TSP问题的动态规划求解
  • ¥25 kubelet.service: Failed with result 'exit-code'.
  • ¥15 bitvise黑框内一键部署v2ray提示账户没有root怎么解决
  • ¥15 车型识别以及相似度匹配中细节特征提取以及图像模糊问题
  • ¥15 怎么用鸿蒙的ArkTs写出来啊
  • ¥30 websocket服务端多线程通信
  • ¥15 JNA 方法调用.dll异常
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部