Woocommerce get Product id using product SKU Woocommerce get Product id using product SKU wordpress wordpress

Woocommerce get Product id using product SKU


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 )


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


WooCommerce product is a special post type. Because of this WP_Query might be used to find product by SKU and other parameters. This might be used as an alternative when you need to restrict your search by some other criterias.

For example you might want to specify language if you use Polylang (or other plugins) for site translations. Or you can restrict search by product type.

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

Example code to find product by SKU using WP_Query (with restriction by product type and language):

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