Woocommerce gets product identifier using SKU product

I am working on a separate template page where the page receives a woocommece product sku using a custom Wordpress message field. I need to get the product id for this object to create a woocommece object and do something else, 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(); } 

There is a way to get the product identifier before creating the object, then I can pass the product identifier to the constructor of the WC_Product class and create an object.thank you

+6
source share
3 answers

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; } 
+9
source

WooCommerce 2.3 finally adds support for this in the kernel.

If you use this version, you can call

 wc_get_product_id_by_sku( $sku ) 
+26
source

A WooCommerce product is a special type of message. Because of this, WP_Query can be used to search for a product by SKU and other parameters. This can be used as an alternative when you need to limit your search to other criteria.

For example, you can specify the language if you use Polylang (or other plugins) to translate the site. Or you can limit your search by product type.

They execute a direct SQL query in the WooCommerce get_product_id_by_sku method, which in many cases I find perfectly fine. But it may not work if you use translations, it will return a random product, but not one that is in the current language.

Sample code for finding a product by SKU using WP_Query (with type and language restrictions):

 public function find( string $lang, string $sku ) { $query = [ 'lang' => $lang, 'post_type' => 'product', 'meta_query' => [ [ 'key' => '_sku', 'value' => $sku, 'compare' => '=' ] ], 'tax_query' => [ [ 'taxonomy' => 'product_type', 'terms' => [ 'grouped' ], 'field' => 'name', ] ] ]; $posts = ( new WP_Query() )->query( $query ); return count( $posts ) > 0 ? $posts[0] : null; } 
0
source

Source: https://habr.com/ru/post/969367/


All Articles