4

当购物车中的产品数量发生变化时,我正在尝试触发一个功能。更具体地说,我想在客户修改购物车中的金额时运行此功能。

我正在寻找购物车中剩余的金额,然后拦截更新购物车事件

目前我正在使用:

add_action( 'woocommerce_remove_cart_item', 'my function');

当我按“update_cart”时,它似乎不起作用。有什么建议吗?谢谢!

4

2 回答 2

6

你应该使用有4 个参数的woocommerce_after_cart_item_quantity_update动作钩子。但是当数量变为零时,需要使用动作挂钩(并且有 2 个参数)woocommerce_before_cart_item_quantity_zero

下面是一个工作示例,它将更新数量限制为一定数量并显示自定义通知:

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()方法中,因此无法在钩子中使用该方法,因为它会抛出错误


要在数量设置为零时触发某些操作,请使用:

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
}
于 2018-03-07T09:30:23.070 回答
1

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

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

于 2018-03-07T09:24:26.527 回答