How to get Woocommerce product attributes and variations programmatically

In this article, we are going to be looking at how you can retrieve product attributes and variations programmatically with WooCommerce.

WooCommerce product attributes are an amazing data structure. You as a store owner can use them to create WooCommerce variable product. Thus, products that are within the same line can be accessed with a few clicks. For example, your customer can select a t-shirt size, without browsing through many different shirts. You can simply pick the size from the product page. The same goes for other variations of products such as size, capacity, requirements, colors, and model.

Sometimes, though, we need more. These static attributes may not do what we need. Or maybe we need to get and change the WooCommerce variation values for an even better user experience. In this case, we need to know how to programmatically access, edit and display these multiple variations.

And that is our goal in this article. We walk you through the concepts of WooCommerce product attributes. By the end of the day, you should be able to use attributes and variations in your WooCommerce store.

Let’s get started!

woocommerce-attributes

What are the WooCommerce product attributes and variations?

It is important to keep in mind the concept of a WooCommerce product attribute, and a WooCommerce product variation. They are similar concepts and they can work together, but to use them effectively this concept needs to be clear.

The simple answer is attributes are the categories and options of a product. Variation is a single product type, picking a specific value for each of the different possible attributes.

This may still be confusing, but there’s no better way to learn than doing. Thus, let’s open your WooCommerce dashboard and create a new product. Make sure you pick the variable product option instead of the simple product:

Create a WooCommerce product with attributes and variations

Now we are creating our product. This example is for a print store. There you have a product with different sizes and materials. You could add as many attributes as you want, such as different glass types, paper, and frameless prints. But for now, let’s stick with the color and material product attributes to make it easier. Then in your product setup you go ahead and add your attributes, using them for your variations as well:

Add WooCommerce attributes and use them in your variations

Make sure you add all the possible values for these attributes. In our case colors are brown or blue, and materials are plastic, metal or wood. Up until this point, you still have a simple product. Your customers would be able to see these attributes, but they won’t be able to select any of them.

In fact, you could use the product attributes as an equivalent of the custom fields. The caveat is that WooCommerce displays product attributes by default, while custom fields can be hidden. And, of course, WooCommerce product attributes are used for WooCommerce variation selection.

To allow user selection, we set our variations based on these attributes. Each of our variations is a combination of the possible WooCommerce product attributes. Let’s create a few of them now

Create each of your WooCommerce variations for products

 

These variations are in fact products themselves. You can add different prices, sale options, stock control, weight, dimensions, and downloads. Therefore, customers buy a WooCommerce product variation, never an attribute.

Sidenote: You can track which attributes and variations are the most popular for each WooCommerce product with the WooCommerce product sales reports of Users Insights:

WooCommerce top ordered variations report

WooCommerce top ordered variations report filter by date

This report helps you understand which variations of your variable products are popular and identify any ordering trends. Hovering over each bar in the chart shows the variation name and number of orders. You can customize the report for a specific period.

You can also have the same report type but based on the actual variation attributes. It counts the number of orders for each variation attribute, helping you find the most popular ones. The report is a good tool to analyze your customers’ preferences. It displays the all-time data, but can also be filtered by a date range.

WooCommerce top ordered attributes report

WooCommerce top ordered attributes report filter by date

In the end, we have:

  • Attributes
    • Color
      • Brown
      • Blue
    • Material
      • Plastic
      • Metal
      • Wood
    • Variations
      • Brown, Plastic
      • Brown, Metal
      • Brown, Wood
      • Blue, Plastic
      • Blue, Metal
      • Blue, Wood

These differences need to be quite clear, as we are moving to the coding portion of our tutorial. There we learn how to get, display and update our data.

How to get WooCommerce attributes and variations programmatically

Usually, when you have multiple WooCommerce product variations, you need to load them. They can be used in many aspects, such as for a custom design in your frontend or displaying messages. In addition, you may want to favor a specific variation, in case that is the most popular, for example.

For all these ideas, you need to programmatically get the WooCommerce product variations and attributes. Let’s see how to do each of these.

Get WooCommerce attributes programmatically

For attributes, usually, the best way is to use the $product->get_attribute( $name ) method. This returns all values you have for that WooCommerce attribute in that particular product. You can add this call inside the loop or outside of it using the global $product call. To make things easier, we simply edit the /woocommerce/single-product.php file in your theme. If you don’t have this file, you can follow our guide on how to customize WooCommerce.

Add this in your loop:

$attr = $product->get_attribute( 'material' );
echo $attr;

 

And you should have an output similar to “Plastic | Metal | Wood” as a string. This can be used in many ways. For instance, you can have preset messages for each possible material or a link to describe their differences. Here is a quick way to display a custom message for all possible materials (including the ones that aren’t in this product in particular):

$attr = $product->get_attribute( 'material' );
//turn attribute into an array
$attr = explode( '|', $attr );

//setup of possible attributes and their descriptions
$descriptions = array(
  'Plastic' => 'Plastic frames are durable and modern <br/>',
  'Metal' => 'Metal frames are stylish and versatile <br/>',
  'Wood' => 'Wood frames are classic <br/>',
  'Glass' => 'Glass frames modern and discrete <br/>',
);

//double check if there are valid values for our array
if ( is_array($attr) && ! empty($attr) ) {
  //loop through array items
  foreach ( $attr as $att ) {
    //remove spaces added by WooCommerce
    $att = trim($att);
    
    //check if this attribute exists in our description list
    if ( array_key_exists( $att, $descriptions ) ) {
      //display our description
      echo $descriptions[$att];
    }
  }
}

This code has an array of possible messages for each of the WooCommerce product attributes. Then we display an explanation of these attributes and how they affect your final result. It is important to notice that not all products have all the materials. Thus, this code would still work as a flexible way of programmatically customizing WooCommerce attributes.

Get WooCommerce variations programmatically

As each variation is a combination of attributes, you probably have a big list of them on your site. But there are some functions to get all WooCommerce variations and get individual variations as well.

In order to get all variations, we use the $product->get_available_variations() method. This code gets all the possible WooCommerce product variations for the current $product. Thus, it is a good way to check all possibilities and their differences in terms of attributes, product price, and stock. Since the returning array contains all variations and their product attributes, you can access each of their details.

This is how to use it:

$vars = $product->get_available_variations();
var_dump($vars);

 

And this is the usual output, but it loops through all possible variations:

Array (
  [0] => Array (
    [attributes] => Array (
      [attribute_frame-color] => Brown
      [attribute_material] => Plastic
    )

    [dimensions] => Array (
      [length] => 
      [width] => 
      [height] => 
    )
    [display_price] => 10
    [display_regular_price] => 10
    [price_html] => €10,00
    [sku] => 
    [weight] => 
    [...]
  )

  [1] => Array ( [...] )
  [2] => Array ( [...] )
  [...]
)

If you want to change your page based on the variation data selected, we need to get creative. That’s because the product variation is set based on a change event for the product dropdown. Therefore, we need to use some jQuery code if we want to easily track these changes.

First, we need to find a WooCommerce product variation hook. This allows us to add jQuery code just for product pages with variations. Then we can use the ‘woocommerce_before_variations_form’, which is present only for variations. Next, we create our jQuery code to read the variation ID input, and where there’s a change we track it via JS.

add_action( 'woocommerce_before_variations_form', 'ui_display_wc_variation' );
 
function ui_display_wc_variation() {    
   global $product;
  ?>
  <script>
  jQuery(document).ready(function() {
    jQuery( 'input.variation_id' ).change( function(){
      if( jQuery.trim( jQuery( 'input.variation_id' ).val() )!='' ) {
        var variation = jQuery( 'input.variation_id' ).val();
        console.log('Variation ' + variation );
        // your custom code goes here
      }
    });
  });
  </script>
  <?php
}

From there, you can use jQuery itself or even CSS for your changes. For instance, you could add a class to your body, depending on the current variation. This allows for custom designs depending on the variation selected. Imagine if the color of your site changed when your visitor selects a different product color.

Another option is to append HTML elements using jQuery, similar to what we did for the attributes.

Unlock the Full Potential of Your WooCommerce Customer Data

Conclusion

WooCommerce product attributes and variations are tags that you can use to add information to your products. Today we looked into many ways to use the WooCommerce product attributes and variations on your shop page. In addition, we looked into many code examples, and how to load them for your own store. By the end of the day, you are able to gather these examples and work on your own WooCommerce site.

We hope you enjoyed it, and see you again next time!