0

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?

1

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.

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.