Wp_query order by multiple custom fields?

$qry_args = array(
    'post_status' => 'publish', 
    'post_type' => 'event', // Post type
    'posts_per_page' => -1, // ALL posts

    'orderby' => 'meta_value',
    'meta_key' => 'year',
    'order' => 'DESC'

);

add_filter( 'posts_orderby', 'filter_query' );
$all_posts = new WP_Query( $qry_args );
remove_filter( 'posts_orderby', 'filter_query' );

function filter_query( $query ) {
    $query .= ', post_modified DESC';
    return $query;
}

Here is an example that works.
The code above orders all posts of type event:
first DESCENDENT by year,
second DESCENDENT by modified date for posts from same year.

without the second ordering they would remain ordered ASCENDENT if they had the same year.

p.s. year is a custom field added by me to posts of type “Event”

Leave a Comment