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!
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
}