Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce: Get Product Variation ID from Matching Attributes

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

{ 'pa_color'=>'red','pa_size'=>'large'}
like image 274
Subair Avatar asked Oct 27 '25 13:10

Subair


2 Answers

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
    );
}
like image 144
mujuonly Avatar answered Oct 30 '25 05:10

mujuonly


If you want to get details on a particular product or loop, you can use this

Here is the 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
);
like image 35
Satish Rathva Avatar answered Oct 30 '25 04:10

Satish Rathva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!