Post type archives are ordered by date, descending by default. This isn’t always desirable, especially for content whose chronology isn’t important.
There are a few recommended methods for changing the order of custom post type archives, but the best technique I’ve found is this one:
This example specifically changes the custom post type archive order to order by post_title ascending, but it should be pretty easy for you to figure out how to order by another property and direction.
I have found that this technique is more robust and reliable than using the pre_get_posts hook.
Diego Betto says
This not always works. If you filter using tax_query a limited group of items (example 3 red cards out of 21 colored cards, taxonomy “color”) you’ll get 9 cards (number correct), but not all red since are ordered by post_title.
example, items:
– card “A” blue
– card “B” red
– card “C” green
– card “D” red
“`
$cards = get_posts(
[
‘numberposts’ => -1,
‘post_type’ => ‘cards’,
‘tax_query’ => [
[
‘taxonomy’ => ‘color’,
‘field’ => ‘slug’,
‘terms’ => [‘red’],
‘operator’ => ‘IN’
]
],
]
);
“`
expected result:
“B”, “D”
result
“A”, “B”
Hannu Jaatinen says
Where do you put this code?