I was working on a WooCommerce project and needed to get the variation ID of a known product that matches a set of attributes.
Say the product ID is 451 and the set of attributes to match are
[
'attribute_pa_color' => 'blue',
'attribute_logo' => 'No'
];
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
);
}
I hope you find it useful.