I want to order the posts by 2 custom fields in the same call. How is this possible?
This next code order successfully, but only by only 1 NUMBER custom field (not STRING):
add_action('pre_get_posts', function ($q) {
if (
!is_admin() // Target only front end queries
&& $q->is_main_query() // Target the main query only
&& ($q->is_search() || $q->is_post_type_archive('data-base'))
) {
$q->set('meta_key', 'custom_field_1');
$q->set('order', 'DESC');
$q->set('orderby', 'meta_value');
}
});
Update 1:
Currently @Mohammed Yassine CHABLI’s first answer works, but it doesn’t sort by number
, but by String
. That means that “81” will come before “9”, which is not good. Any solution for that?
Resources that might help:
3
Answers
Try this one :
configure the meta query :
In case you want to sort in the same direction :
You need the WP way of providing an expression in the
ORDER BY
;That is, do something to meta_key to convert it into a numeric value.
A possible simple solution would be to format the text as if it were a number.
Samples:
The weight on the performance of the query is to be evaluated.