1

I'm creating a webshop, that imports a lot of products from a csv file. I need to link to available accessories etc., which individually is determined and imported by the respectable products SKU.

I know it is possible to get the product ID with a simple products SKU with this:

wc_get_product_id_by_sku('PRODUCT_SKU');

Is there anyway to do the same, but with a variation sku?

4

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.

1
  • Thanks. Maybe not name it as you have in case WC eventually write a function with the same name ;) – Andrew Schultz Nov 10 '20 at 3:40
0

The simplest way is to get Variation ID using wc_get_product_id_by_sku function then get post parent ID to get Product ID.

$variation_id = wc_get_product_id_by_sku('VARIATION_SKU');
$product_id = wp_get_post_parent_id($variation_id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.