Reputation: 1220
I have a simple Wordpress query that lists my custom post type results.
Currently, they list in order of date the post was created.
I need them to list in the order of a custom field I have named 'release_year' from most recent to oldest.
I am having trouble incorporating that second query to my results.
How do I ensure all posts are sorted by release_year ??
ANy help appreciated.
<?php
$posts = get_posts(array(
'post_type' => 'discography',
'posts_per_page' => -1,
'meta_key' => 'release_category',
'meta_value' => 'album',
'orderby' => 'meta_value',
'order' => 'ASC',
));
if( $posts ): ?>
Upvotes: 2
Views: 6416
Reputation: 19308
You need to order by release_year
however you're specifying release_category
as the meta key therefore it has no way of knowing that you want to use the other key instead.
The main issue you face is you can't have two meta_key
args. Instead you need to make use of the meta_query
argument.
$posts = get_posts(array(
'post_type' => 'discography',
'posts_per_page' => -1,
'meta_key' => 'release_year',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'release_category',
'value' => 'album',
),
),
));
The meta query is used to set the release category and the meta_key
value changed to the key you'd like to order by. I've also set order to meta_value_num
which is important when dealing with numerical values. Finally you need to use descending order.
Further reading: https://codex.wordpress.org/Class_Reference/WP_Meta_Query
https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
Upvotes: 6