Make the variation dropdowns user friendly by changing "Choose an option" to use the attribute name and be more clear.
When you create a variable WooCommerce product and add attributes and variations to the product the product page will have a dropdown for each attribute. If you haven’t specified a default variation, it will show “Choose an option“. I want this to be more user friendly.
A reply on StackOverflow led me to the ‘woocommerce_dropdown_variation_attribute_options_args‘ filter. The solution there didn’t work for me but, after some experiments with error_log() and var_export() I noticed a pattern in the values in the $args array.
Global and Custom Attributes
You can create global attributes in Products/Attributes. These can be applied to variable products and give you consistent attributes.
You can also create custom attributes on a per product level.
The screenshot shows a custom attribute (Size, with terms separated with pipe symbols) and a global attribute (Collar Colour, with terms chosen from the available ones).
Long Code then Short Code
I first implemented this change on a site that I am working on. It has Size and Colour attributes used on multiple products. I noticed that the attribute was given a name with a pa_ prefix e.g. ‘pa_size‘. I wrote code to check for those attribute names and returned the appropriate string.
For a custom product attribute I saw that the nice attribute name (not the lowercase slug) was in the passed $args array so that was easy.
I then wrote a slightly complicated line of code to convert ‘pa_size‘ to ‘Size‘
The Simple Code
I noticed that the attribute name was displayed above the dropdown so I did a short search of the WooCommerce source and found that it used the ‘wc_attribute_label() function. I was able to simplify my code to one line: