如何从 "woocommerce_cart_item_removed" 钩子中找出产品 ID?

How to find out product id from "woocommerce_cart_item_removed" hook?

我有密码

add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart' );
function after_remove_product_from_cart($removed_cart_item_key, $instance) {
    $product_id = $removed_cart_item_key['product_id'];
}

我想找到一种使用 $removed_cart_item_key 获取产品 ID 或实际产品对象本身的方法。你怎么做呢?我找不到任何参考资料,谢谢。

应该是这样的...

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

因为它发生在购物车项目被删除之前,您需要使用 woocommerce_remove_cart_item 而不是 woocommerce_cart_item_removed 来检索此产品项目。

add_action( 'woocommerce_remove_cart_item', 'after_remove_product_from_cart', 10, 2 );
function after_remove_product_from_cart($removed_cart_item_key, $cart) {
    $product_id = $cart->cart_contents[ $removed_cart_item_key ]['product_id'];
}

from helgatheviking

您可以使用此方法获取从购物车中移除的商品的产品 ID,它对我有用

$product_id = $购物车->cart_contents[$cart_item_key]['product_id'];