WordPress query by multiple Custom fields and order by date

@Uffo I would say your args are wrong, should be something like:

$args = array(
    'post_type' => 'Event',
    'posts_per_page' => 1000,
    'meta_query'=> array(
        array(
            'key'=>'event_informations_show_on_the_homepage',
            'value'=> 'Show on the homepage',
            'compare' => '=='
        )
    ),
    'meta_key'=>'event_informations_date',
    'orderby'=>'meta_value_num', 
    'order'=>'ASC'
);

The way you did it, it’s just the last meta_key that will be used both for filtering the query and to order. I’m not 100% sure if this way will work but give it a try.

Hope I’ve helped.


So I think you will need to filter the Group By SQL statement to make it work the way you want, something like that:

$args = array(
    'post_type' => 'Event',
    'posts_per_page' => 1000,
    'meta_query'=> array(
        'relation' => 'OR',
        array(
            'key'=>'event_informations_show_on_the_homepage',
            'value'=> 'Show on the homepage',
            'compare' => '=='
        ),
        array(
            'key'=>'event_informations_date',
        )
    ),
    'orderby'=>'meta_value_num', 
    'order'=>'ASC'
);

add_filter('posts_orderby', 'edit_posts_orderby');

function edit_posts_orderby($orderby_statement) {
    $orderby_statement = "mt1.meta_value+0 ASC";
    return $orderby_statement;
}

Leave a Comment