Woocommerce get Product id using product SKU

Suneth Kalhara

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

pmandell

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Woocommerce.NET + C#: get the ID of product from SKU

SKU update on WooCommerce product

Woocommerce get product sku for single product page in functions.php

Get WooCommerce product SKU in product pages meta box

Get slug from a woocommerce product using a product id

WooCommerce get product attributes with given product ID

Woocommerce Get Product Values by ID

Get a specific product by id in WooCommerce

woocommerce get product category id

Woocommerce, get main product id

Disable WooCommerce SKU on Product Page

Get the product object from sku and update the price in WooCommerce

How to get the product sku from order items in Woocommerce

Get sku from Woocommerce product bookings in a WP_Query

Get the category name from a WooCommerce product using the product id or the category id

Get also WooCommerce product category thumbnail Id using a SQL query

Get WooCommerce product purchase date from a product Id for a user Id

Get the product ID in woocommerce_product_get_image filter hook

Get SKU of product in cart Wordpress

Get SKU of each product in an order

Get product variation id by their product attributes slug values pairs in Woocommerce

How to get the grouped product ID from a linked product in woocommerce

Get in WooCommerce cart the product ID of a cart item

How to get woocommerce orders by product ID wordpress?

Get the Product ID in email template: WooCommerce

Wordpress / Woocommerce Get single product photo by ID

Get the author ID of each product in Woocommerce cart

PHP: Get image to link to Product id (woocommerce)

Woocommerce how to display products by product SKU

TOP Ranking

HotTag

Archive