Let’s say there’s a product attribute "brand" with the following terms:
- Brand A
- Brand B
- Brand C
Let’s also say the menu order of these terms in products > attributes > size have been ordered as such:
- Brand C
- Brand A
- Brand B
How can I sort the products on the shop page by the attribute menu order? So for example:
- Brand C product
- Brand A product
- Brand B product
Assume each product only has a single brand attribute term.
So far I’ve figured the code will likely involve modifying the query using the pre_get_posts
hook, but I’m having difficulty customizing the order in such a way.
2
Answers
Honk31's answer worked well for me. I just had to modify it a little bit.
Another step that is needed is to use the Simple Custom Post Order plugin. The plugin adds a
term_order
column to the terms table that the code uses to sort by. Drag and drop to change the terms order in products > attributes > brand. I actually had to move all of the terms around to get the order to sort correctly.WooCommerce attributes do have a drag & drop functionality already, though. Perhaps it is possible to do something similar without that plugin.
Since get_terms() is returning the order we have set for our attributes we can get those ids and use them as sorting.
From there we can use
woocommerce_product_query
to modify our query.And finaly set the order of our query to be by
term_id
ASC or DESC.Here is my solution