I have an acf field called totalviews. It stores the total views number for each page i have. The field is number/numeric. Then I am trying to find the page with most views so i sort the number i store in acf field using a wp_query inside functions.php file but i get wrong sort order results. Its messed up not ASC nor DESC ... is my query right? Any help appreciated.
$q_args = array(
'category__not_in' => array( 62,63,170,175,176,171,180 ),
'post_type' => 'post',
'posts_per_page'=>'-1',
'order' => 'DESC',
'meta_query' =>array(
array(
'key' => 'picture_url',
'value' => 'none',
'compare' => '!='
),
array(
'key' => 'totalviews',
'value' => '0',
'compare' => '>=',
'type' => 'NUMERIC',
'orderby' => 'meta_value_num'
)
)
);
$query = new WP_Query( $q_args );
I have an acf field called totalviews. It stores the total views number for each page i have. The field is number/numeric. Then I am trying to find the page with most views so i sort the number i store in acf field using a wp_query inside functions.php file but i get wrong sort order results. Its messed up not ASC nor DESC ... is my query right? Any help appreciated.
$q_args = array(
'category__not_in' => array( 62,63,170,175,176,171,180 ),
'post_type' => 'post',
'posts_per_page'=>'-1',
'order' => 'DESC',
'meta_query' =>array(
array(
'key' => 'picture_url',
'value' => 'none',
'compare' => '!='
),
array(
'key' => 'totalviews',
'value' => '0',
'compare' => '>=',
'type' => 'NUMERIC',
'orderby' => 'meta_value_num'
)
)
);
$query = new WP_Query( $q_args );
Share
Improve this question
asked Jul 11, 2019 at 1:17
stefanosnstefanosn
1339 bronze badges
6
|
Show 1 more comment
1 Answer
Reset to default 3From your comment:
it worked without the
array( 'key' => 'picture_url', 'value' => 'none', 'compare' => '!=' )
but I need to include it in the query... is it possible?
Yes, using named sub-meta queries like so:
$q_args = [
// ... other args here ...
'meta_query' => [
'picture_url' => [ 'key' => 'picture_url', 'value' => 'none', 'compare' => '!=' ],
'totalviews' => [ 'key' => 'totalviews', 'value' => '0', 'compare' => '>=', 'type' => 'NUMERIC' ],
],
'orderby' => 'totalviews', // set this to a key in the above meta queries
'order' => 'DESC',
];
The orderby
parameter can also be an array:
'orderby' => [
'totalviews' => 'DESC', // sort by meta_query key
'picture_url' => 'ASC', // sort by meta_query key
'date' => 'DESC', // sort by the post date
]
And (once again), orderby
is not a valid argument for an array in the meta_query
array. See here for more details.
orderby
doesn't belong in ameta_query
. Instead, it's the main args and should be placed after themeta_query
. – Sally CJ Commented Jul 11, 2019 at 1:30'meta_query' => array( ... ), 'orderby' => 'meta_value_num'
– Sally CJ Commented Jul 11, 2019 at 1:50