How I get product variation id from custom product loop. I have variation attribute like,
{ 'pa_color'=>'red','pa_size'=>'large'}
How I get product variation id from custom product loop. I have variation attribute like,
{ 'pa_color'=>'red','pa_size'=>'large'}
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
);
}
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
);