简体   繁体   English

哪个挂钩可以更改WooCommerce购物车页面中的数量更新?

[英]Which Hook to alter quantity update in WooCommerce cart page?

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. 当我按“ update_cart”时,它似乎不起作用。 Any advice? 有什么建议吗? Thank you! 谢谢!

You should use woocommerce_after_cart_item_quantity_update action hook that has 4 arguments . 您应该使用具有4个参数的 woocommerce_after_cart_item_quantity_update操作挂钩 But when quantity is changed to zero, woocommerce_before_cart_item_quantity_zero action hook need to be used instead (and has 2 arguments) . 但是,当数量更改为零时,需要改为使用woocommerce_before_cart_item_quantity_zero操作钩子 (并且具有2个参数)

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) . 此代码在您的活动子主题(或主题)的function.php文件上 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 . 由于此挂钩位于WC_Cart set_quantity()方法中因此无法在挂钩内使用该方法,因为它将抛出错误


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
}

Maybe this hook? 也许这个钩子? do_action( 'woocommerce_after_cart_item_quantity_update', $cart_item_key, $quantity, $old_quantity );

http://hookr.io/actions/woocommerce_after_cart_item_quantity_update/ http://hookr.io/actions/woocommerce_after_cart_item_quantity_update/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM