I am going to share a quick snippet today on this post. I was working on a WooCommerce site that uses a few attributes. These attributes has hundreds of values.

Recently I’ve added a few more values to a few products belonging to a few particular categories. I’ve used a snippet for that task as well which you can find on this article (link will be added soon).

So, The new attribute values I added was starting with the letter B but they were appearing at the bottom of all the options, because I just appended the new item values at the end of existing values. But however, the new attributes needed to be displayed in proper placement, otherwise it will be nearly invisible to customers as all the other values are added there in proper sort order.

To fix this, I started analyzing the available hooks and then came up with the solution to sort the values before outputting the dropdowns containing attribute values.

This is the code that allows you to sort attribute values of woocommerce product

Shit! That’s an Image!

Above is a screenshot of code but obviously I don’t want you to ready and write the whole portion of code 😛 Let’s just copy the code below and paste it in your theme’s functions.php file or

Sorting only for specific attributes ?

The code above is useful if you want to sort all the attributes but what if you just want to apply the sorting to only a few specific attributes ?

I needed to apply for only specific attributes, so I have the solution for that as well 😉

Here’s the code to restrict to only specific attributes:

How To Use/Customize ?

Let’s get into some details of the shared code to help you understand and use it properly.

The code above takes the array of attribute values and sort the array using asort function. Which means the array will be sorted in ASCENDING order. If you need to change the sort order, please check this page for possible alternatives.

All the other settings can just stay same if you’re using the all attribute version of code.

If you’re using the specific attributes version, You’ll need to replace the Attribute Name with your real attribute name.

Having any Issue ?

Feel free to comment if you are having any kind of issues to understand the solution or have any question. I’ll try to reply asap.