【问题标题】:How to find out product id from "woocommerce_cart_item_removed" hook?如何从“woocommerce_cart_item_removed”挂钩中找出产品 ID?
【发布时间】:2016-04-21 05:46:39
【问题描述】:

我有代码

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 或实际产品对象本身的方法。你怎么做呢?我找不到任何参考资料,谢谢。

【问题讨论】:

    标签: php wordpress woocommerce cart


    【解决方案1】:

    应该是这样的……

    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' ];
    }
    

    【讨论】:

    • 谢谢,新手问题:10 和 2 是干什么用的?
    • 我不得不使用 'woocommerce_cart_item_removed_title' 钩子。只是一个顺便说一句。在这样做的过程中,我只需$cart['some property'] 就可以检索我正在寻找的项目,因为$cart 只给出了被删除的项目......
    【解决方案2】:

    因为它发生在购物车商品被移除之前,您需要使用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'];
    }
    

    helgatheviking看到this source

    【讨论】:

    • 我自己的问题其实可以用这个解决方案,和OP差不多。
    【解决方案3】:

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

    $product_id = $cart->cart_contents[$cart_item_key]['product_id'];

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2018-12-06
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      相关资源
      最近更新 更多