4

How I get product variation id from custom product loop. I have variation attribute like,

{ 'pa_color'=>'red','pa_size'=>'large'}
starball
  • 20,030
  • 7
  • 43
  • 238
Subair
  • 91
  • 1
  • 2
  • 8

2 Answers2

18

Set of attributes to match are

[
    'attribute_pa_color' => 'blue',
    'attribute_pa_size' => 'small',
];

Below is the function I ended up creating to achieve this:

/**
 * Find matching product variation
 *
 * @param $product_id
 * @param $attributes
 * @return int
 */
function find_matching_product_variation_id($product_id, $attributes)
{
    return (new \WC_Product_Data_Store_CPT())->find_matching_product_variation(
        new \WC_Product($product_id),
        $attributes
    );
}
mujuonly
  • 11,370
  • 5
  • 45
  • 75
  • 5
    I just wanted to add a noteworthy comment about this answer. If you have a dynamic variation with multiple attributes, and one or multiple can contain the value of "any", then you must pass in a blank attribute as part of your array of attributes. **Example:** ` ( new \WC_Product_Data_Store_CPT() )->find_matching_product_variation( $product, array( 'attribute_pa_style' => '', 'attribute_pa_color' => '', 'attribute_pa_logo' => '', 'attribute_pa_size' => 'small', ) ); ` – Michael Ecklund Aug 12 '19 at 13:10
3

Here full Example Code Of find_matching_product_variation !

$product_id = 1;       //Added Specific Product id

$match_attributes =  array(
    "attribute_pa_color" => 'blue',
    "attribute_pa_size" => 'Large'
);

$data_store   = WC_Data_Store::load( 'product' );
$variation_id = $data_store->find_matching_product_variation(
  new \WC_Product( $product_id),$match_attributes
);