Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce get Product id using product SKU

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

like image 287
Suneth Kalhara Avatar asked May 16 '14 04:05

Suneth Kalhara


People also ask

How do I find my product ID in WooCommerce?

A WooCommerce Product ID is sometimes needed when using shortcodes, widgets, and links. To find the ID, go to Products and hover over the product you need the ID for. The product ID number is displayed.

How do I get a product slug in WooCommerce?

Go to WooCommerce > Settings > Custom Permalinks. 3. In the “product permalinks” section choose “Product slug alone” or “Product slug with category name” if you want to include category slug into URL.


2 Answers

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 )
like image 101
Akshay Agarwal Avatar answered Sep 22 '22 08:09

Akshay Agarwal


You can use this function (found here). Google is your friend!

function get_product_by_sku( $sku ) {

    global $wpdb;

    $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );

    if ( $product_id ) return new WC_Product( $product_id );

    return null;
}
like image 40
pmandell Avatar answered Sep 24 '22 08:09

pmandell