Skip to content
Advertisement

Get product variation id by their product attributes slug values pairs in Woocommerce

How can I get product variation ID by taxonomy terms?

For example if I have two taxonomies and their terms:

1) Size: medium, large
2) Color: blue, green

And my product variations:

Variation id 1: medium > blue
Variation id 2: medium > green
Variation id 3: large > blue
Variation id 4: large > green

I would like to get variation ID of this terms combination medium > green.

Answer

The following function uses a very light SQL query to get the variation ID for from a variable product for defined product attributes “color” and “size” term slugs:

function get_product_variation_id( $size, $color, $product_id = 0 ) {
    global $wpdb;

    if ( $product_id == 0 )
        $product_id = get_the_id();

    return $wpdb->get_var( "
        SELECT p.ID
        FROM {$wpdb->prefix}posts as p
        JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
        JOIN {$wpdb->prefix}postmeta as pm2 ON p.ID = pm2.post_id
        WHERE pm.meta_key = 'attribute_pa_color'
        AND pm.meta_value LIKE '$color'
        AND pm2.meta_key = 'attribute_pa_size'
        AND pm2.meta_value LIKE '$size'
        AND p.post_parent = $product_id
    " );
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


USAGE (2 cases examples):

  1. From a defined variable product ID (where 746 is the parent variable product ID):

    $variation_id = get_product_variation_id( ‘large’, ‘blue’, 746 );

  2. On the variable product single product page (No need to define the variable product ID):

    $variation_id = get_product_variation_id( ‘large’, ‘blue’ );