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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用