How to get the product sku from order items in Woocommerce

Александра Кузнецова picture Александра Кузнецова · Jun 10, 2018 · Viewed 7.9k times · Source

For Api on page "woocommerce_thankyou" need get sku. I have:

$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;

But not works.

Answer

Bjorn picture Bjorn · Jun 10, 2018

I think you're fiddling around on the actual template page ;-) In Wordpress we mainly use action hooks to accomplish tasks like this.

Try this, place it in the (child) theme functions.php.

NOTE: only for 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 

}

Regards, Bjorn