Woocommerce get Product id using product SKU

Suneth Kalhara picture Suneth Kalhara · May 16, 2014 · Viewed 35.4k times · Source

I'm working on a separate templates page, which page gets woocommece product sku using custom field of wordpress post. i need to get product id of that sku for create woocommece object and do further things, here is my code.

global $woocommerce;
//this return sku (custom field on a wordpress post)
$sku=get_field( "product_sku" );
if($sku!=''){
  //need to create object, but using sku cannot create a object, 
  $product = new WC_Product($sku); 
  echo $product->get_price_html();
}

is there way to get product id before create object, then i can pass the product id to WC_Product class constructor and create object.thank you

Answer

Akshay Agarwal picture Akshay Agarwal · Jan 2, 2015

WooCommerce 2.3 finally adds support for this in core.

If you are using this version, you can call

wc_get_product_id_by_sku( $sku )