I am learning WP_query and recently ran into a problem.

I need to do a query where i first filter trough one or more custom fields, which works great thanks to meta_query.

However, i also need it to order by multiple custom fields.

(Like in sql you can write “ORDER BY field ASC, field2 DESC”)

This is what i have so far:

$args=array(
    'post_type' => 'personer',
    'meta_query' => array(
        array(
            'key' => 'p_seller',
            'value' => 'Y',
            'compare' => '='
        )
    ),
    'meta_key' => 'p_region',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'post_status' => 'publish',
    'posts_per_page' => 999,
    'caller_get_posts'=> 1
);

It returns rows with p_seller set to Y and order by p_region. I’d also like to add a second orderby which order them by p_lastname after region. Or even better – p_region, p_lastname, p_firstname. All ascending, but i’d love to know how to combine ASC and DESC aswell 🙂

I have done some googling, but most people seem to write about multiple fields for filtering, which i got. Or they do space out in custom SQL queries, which i hope i can get by without? 🙂

4 Answers
4

$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 Reply

Your email address will not be published. Required fields are marked *