menu

arrow_back How do I sort by custom field?

by
1 vote
I am trying to sort categories by meta field position, but the problem is that if you sort by meta field, the query will not take into account other categories without this meta field.

Tried this:
$categories = get_terms([
'taxonomy' => 'nwb_cat',
'hide_empty' => false,
'meta_query' => [
'relation' => 'OR',
'position' => [
'key' => 'position',
'compare' => 'EXISTS'
],
'position_not' => [
'key' => 'position',
'compare' => 'NOT EXISTS'
],
],
'orderby' => [
'position' => 'ASC',
]
]);
Result: no sorting takes place Tried this:
$categories = get_terms([
'taxonomy' => 'nwb_cat',
'hide_empty' => false,
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_key' => 'position',
]);
Result: The sorting works correctly, but only those categories that have the meta field position are displayed. PS. This field will not be filled by default. How can this issue be resolved?

2 Comments

Dima Polos , sorting works, but not all categories are displayed
In the first option, add the meta_key => "position"
It's supposed to work

1 Answer

by
0 votes
Try

'orderby' => [
'position' => 'DESC',
'position_not' => 'ASC',
]

1 comment

Didn't help