I am having a little problem. I am trying to get the latest 12 post by a custom meta field. Out of those 12 posts, I want to order them by post date. So first I pull 12 posts out using a custom meta field and ordering them to find the latest through the meta field. Once I have them, then I want to re-order them with latest post.
Here is my current code, I don't know how I can put two order-bys in one query...
$recentEpisodes12 = new WP_Query(array(
'posts_per_page' => 12,
'post_type' => 'post',
'meta_key' => 'air_date',
'order' => 'DESC',
'orderby' => 'meta_value_num',
'meta_query' => array(
array(
'key' => 'air_date',
),
array(
'key' => 'already_aired',
'value' => 'yes',
'compare' => '='
)
),
));
In WordPress 4.2 and up, ordering by one or more custom fields was made much easier. See this link for examples: https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/
You can even order one column ASC and another DESC by passing an array to orderby now:
So if you want to order them by post date, why do you need a meta field for that? Once you get the 12 latest posts by meta value, is the
air_date
somehow different from the post date?Worth noting:
posts_per_page
doesn't limit the total number of returns. It just tells WordPress when to split into a new page.Something like this should work based on what you described in your original post.
According to the Codex, you simply need to separate them by a space:
In your case, that would look like:
EDIT: Okay, it seems like you're trying to do something a bit more complex here. This is how I interpret it, correct my if I'm wrong:
air_date
(in descending order, newest first).air_date
.date
.What
orderby
does is basically:air_date
.air_date
values, order those bydate
.The difference is that you only want to distinguish by
air_date
, whereas the normal usage oforderby
uses both criteria to determine which items end up in the result.I don't know an easy way to solve this, though. However, since you only want to change the display order of the resulting items, you could just sort those yourself. You can use
get_posts
instead ofWP_Query
and sort the results array using PHP'susort