如果用户在 WooCommerce 购物车中将数量更改为 0,则获取项目的产品 ID

Get The Product Id of An Item If User Changes Quantity to 0 in WooCommerce Cart

我正在尝试找出一种方法来从购物车页面获取数量减少为 0 的商品的产品 ID。

我挂接到 woocommerce_after_cart_item_quantity_update 之后,如果用户将数量更改为 0 以外的任何值,它就会触发。:(

function action_woocommerce_after_cart_item_quantity_update( $cart_item_key, $quantity, $old_quantity ) {
    var_error_log([$cart_item_key, $quantity, $old_quantity]);
};

add_action( 'woocommerce_after_cart_item_quantity_update', 'action_woocommerce_after_cart_item_quantity_update', 10, 3 );


function var_error_log( $object=null ){
    ob_start();                    // start buffer capture
    var_dump( $object );           // dump the values
    $contents = ob_get_contents(); // put the buffer into a variable
    ob_end_clean();                // end capture
    error_log( $contents );        // log contents of the result of var_dump( $object )
}

还有其他方法吗?

编辑:

woocommerce_cart_item_removed 挂钩也不好,因为它仅在用户单击删除按钮时运行,而不是在该项目的数量更改为 0 时运行。

并且 woocommerce_cart_item_removed 挂钩的发生方式与 woocommerce_cart_item_removed 挂钩类似。

试试这个钩子,

add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart', 10, 2 );
function after_remove_product_from_cart($removed_cart_item_key, $instance) {
    $line_item = $instance->removed_cart_contents[ $removed_cart_item_key ];
    $product_id = $line_item[ 'product_id' ];
}

从购物车中移除商品时将触发此事件。 更多信息,

希望对您有所帮助。

这次事件有一个单独的钩子:

woocommerce_before_cart_item_quantity_zero

function woocommerce_before_cart_item_quantity_zero_vvvrbg45kt45($cart_item_key) {
    global $woocommerce;
    $cart_item = $woocommerce->cart->get_cart_item( $cart_item_key );
    $product_id = $cart_item['product_id'];
}
add_action( 'woocommerce_before_cart_item_quantity_zero', 'woocommerce_before_cart_item_quantity_zero_vvvrbg45kt45' );