EDIT: It seems that you can now use wc_get_product_id_by_sku() to retrieve a product_variation without any problems, see the other answer below.
I was stuck on a very similar problem. I couldn't find anything in the woocommerce code that would let you directly look up the parent product from the variation sku.
But, as product variations are stored in the wp_posts
table with the type product_variation
, and the SKUs are stored in the wp_post_meta
table, it's easy to look up the product variation using a meta query with the get_posts()
wordpress function.
$args = array(
'post_type' => 'product_variation',
'meta_query' => array(
array(
'key' => '_sku',
'value' => 'PRODUCT_SKU',
)
)
);
$posts = get_posts( $args);
This should return your matching product_variation
custom post type.
Once you have this then you can look up the parent product using the column post_parent
that WooCommerce uses to link a variation to the parent variable product.
Turning that into a function is pretty straight forward:
function wc_get_product_id_by_variation_sku($sku) {
$args = array(
'post_type' => 'product_variation',
'meta_query' => array(
array(
'key' => '_sku',
'value' => $sku,
)
)
);
// Get the posts for the sku
$posts = get_posts( $args);
if ($posts) {
return $posts[0]->post_parent;
} else {
return false;
}
}
I use this in my site and it works great. Hope that helps.