你应该使用woocommerce_after_cart_item_quantity_update动作挂钩 https://docs.woocommerce.com/wc-apidocs/source-class-WC_Cart.html#1192具有4 个参数。但当数量变为零时,woocommerce_before_cart_item_quantity_zero动作挂钩 https://docs.woocommerce.com/wc-apidocs/source-class-WC_Cart.html#1187需要改用(并且有 2 个参数).
下面是一个工作示例,它将更新数量限制为一定数量并显示自定义通知:
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' );
}
}
此代码位于活动子主题(或主题)的 function.php 文件中。经过测试并有效。
由于该钩子位于WC_Cart set_quantity() method https://docs.woocommerce.com/wc-apidocs/source-class-WC_Cart.html#1177-1200, 不可能在钩子内使用该方法,因为它会抛出错误.
要在数量设置为零时触发某些操作,请使用:
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
}