在 WooCommerce 3+ 订单项中获取产品 ID

问题描述:

我正在尝试获取 woocommerce 感谢页面 order_id.使用下面的代码.但不幸的是我无法得到它.

I am trying to get woocommerce thank you page order_id. Using the code below. But unfortunately I can't get it.

    add_action( 'woocommerce_thankyou', 'bbloomer_check_order_product_id');

function bbloomer_check_order_product_id( $order_id ){
$order = new WC_Order( $order_id );
$items = $order->get_items(); 
foreach ( $items as $item ) {
   $product_id = $item['product_id'];
      if ( $product_id == XYZ ) {
        // do something
      }
}
}

此代码对于 WooCommerce 版本 3+ 已过时.你应该改用:

This code is outdated for WooCommerce version 3+. You should use instead:

add_action( 'woocommerce_thankyou', 'check_order_product_id', 10, 1);
function check_order_product_id( $order_id ){
    # Get an instance of WC_Order object
    $order = wc_get_order( $order_id );

    # Iterating through each order items (WC_Order_Item_Product objects in WC 3+)
    foreach ( $order->get_items() as $item_id => $item_values ) {

        // Product_id
        $product_id = $item_values->get_product_id(); 

        // OR the Product id from the item data
        $item_data = $item_values->get_data();
        $product_id = $item_data['product_id'];

        # Targeting a defined product ID
        if ( $product_id == 326 ) {
            // do something
        }
    }
}

代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中.

此代码经过测试,适用于 WooCommerce 版本 3+

This code is tested and works for WooCommerce version 3+

参考:如何获取 WooCommerce 订单详情