如何从 Woocommerce 中的订单商品中获取产品 sku

How to get the product sku from order items in Woocommerce

第 "woocommerce_thankyou" 页上的 Api 需要获取 sku。 我有:

$order = wc_get_order( $order_id ); 
foreach ($order->get_items() as $item_key => $item_values):
   $product = new WC_Product($item_id);
   $item_sku[] = $product->get_sku();
endforeach;

但是不行。

我认为您是在实际模板页面上摆弄 ;-) 在Wordpress中我们主要使用action hooks来完成这样的任务。

试试这个,把它放在(儿童)主题中 functions.php

注意:仅适用于 WooCommerce 3+

add_action( 'woocommerce_thankyou', 'order_created_get_skus', 10 );

function order_created_get_skus($order_id){

  $item_sku = array();
  $order = wc_get_order( $order_id ); 

  foreach ($order->get_items() as $item) {
    $product = wc_get_product($item->get_product_id());
    $item_sku[] = $product->get_sku();
  }

  // now do something with the sku array 

}

此致,比约恩