在 WooCommerce 3+ 订单项中获取产品 ID [英] Get the product ID in WooCommerce 3+ Order items

查看:74
本文介绍了在 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 订单详情

这篇关于在 WooCommerce 3+ 订单项中获取产品 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆