'ACF Ordering posts by number field treated like a string
Ordering posts by number field treated like a string. I have a custom number field (by ACF). and set my several posts as like 99 98 97 to show first in homepage. but the ordering after 10 is wrong. After searching i need to use orderby meta_value_num instead of meta_value. I have multiple meta values in the array. How to apply?
shown as: 99 98 97 …… 92 91 90 9 89 88 …. 80 8 79 78…
other example: 9 82 6 4 16 15 14
desired: 82 16 15 14 9 6 4
How can i fix this?
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post' ) {
$query->set('meta_query', array(
'myordernumber' => array(
'key' => 'myordernumber',
)
));
$query->set('orderby',array(
'myordernumber' => 'DESC',
'date' => 'DESC'
));
}
// return
return $query;
Solution 1:[1]
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post' ) {
$query->set('meta_query', array('myordernumber' => array(
'key' => 'myordernumber',)));
$query->set('orderby', array('meta_value_num' => 'DESC',
'date' => 'DESC') );
}
return $query;
Related: https://make.wordpress.org/core/2014/08/29/a-more-powerful-order-by-in-wordpress-4-0/
https://developer.wordpress.org/reference/hooks/pre_get_posts/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | osunkaya |
