How to get variation id by attributes in woocommerce?

by lindsey.homenick , in category: PHP CMS , 4 months ago

How to get variation id by attributes in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 4 months ago

@lindsey.homenick 

You can get the variation ID by using the WC_Product_Variable class in WooCommerce. Here is an example code snippet that shows how to get the variation ID by attributes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Get the product
$product = wc_get_product( $product_id );

// Get the variations of the product
$variations = $product->get_available_variations();

// Define the attributes for the variation you are looking for
$attributes = array(
    'color' => 'Red',
    'size' => 'Medium'
);

// Loop through the variations to find the matching one
foreach ( $variations as $variation ) {
    $variation_attributes = $variation['attributes'];
    
    if ( $attributes === $variation_attributes ) {
        $variation_id = $variation['variation_id'];
        break;
    }
}

// Print the variation ID
echo 'The variation ID is: ' . $variation_id;


In this code snippet, replace 'color' => 'Red' and 'size' => 'Medium' with the attributes you are looking for in the variation. The code will loop through all the available variations of the product and compare the attributes to find the matching variation ID.