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