Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by multiple meta keys?

Tags:

I’m using a custom loop to display my events on a page, I get it fine ordering by the event start date using the below:

$args = array( 
    'post_type' => 'event',
    'order' => 'ASC',
    'orderby' => 'meta_value',
    'meta_key' => '_event_start_date');
$loop = new WP_Query( $args );

But the meta_key option only allows one value. How to use two values (_event_start_date and _event_start_time)?

like image 574
user1280853 Avatar asked Jul 19 '13 11:07

user1280853


2 Answers

This is something that WordPress added support for in 4.2: https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/

In your case you'll probably want to do something like this:

$args = array(
    'post_type'  => 'event',
    'meta_query' => array(
        'relation' => 'AND',
        'event_start_date_clause' => array(
            'key'     => '_event_start_date',
            'compare' => 'EXISTS',
        ),
        'event_start_time_clause' => array(
            'key'     => '_event_start_time',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => array(
        'event_start_date_clause' => 'ASC',
        'event_start_time_clause' => 'ASC',
    ),
);

$loop = new WP_Query( $args );
like image 125
Wes Moberly Avatar answered Sep 29 '22 23:09

Wes Moberly


You have to use meta_query at add your meta keys as everyone said, but also you have to customize order by function.

$args = array(
    'post_type' => 'event',
    'meta_key' => '_event_start_date',
    'meta_query' => array(
        array('key' => '_event_start_date'),
        array('key' => '_event_start_time')
    ),
);

add_filter('posts_orderby','customorderby');
$loop = new WP_Query( $args );
remove_filter('posts_orderby','customorderby');

And put this on your functions.php

function customorderby($orderby) {
    return 'mt1.meta_value ASC, mt2.meta_value ASC';
}

You can read more at http://dotnordic.se/sorting-wordpress-posts-by-several-numeric-custom-fields/

like image 22
Kiyan Avatar answered Sep 29 '22 21:09

Kiyan