How to combine meta_query and orderby date meta in WordPress?

I have 3 meta fields, date (date formatted string), location, and consultant.

I can pull the posts and orderby the date field when meta_key is set:

Read More
// get posts
$posts = get_posts(array(
    'post_type'     => 'event',
    'posts_per_page'    => -1,
    'meta_key'      => 'start_date',
    'orderby'       => 'meta_value_num',
    'order'         => 'DESC'
));

However, I have not be able to get this to work with a more complex meta_query:

$args = array(
    'post_type' => 'uppy_events',
    'orderby'       => 'meta_value_num',
    'order'         => 'ASC',

    'meta_query' => array(
        array(
            'key' => $key,
            'value' => array($value),
            'compare' => '>='
            )
        ),
        'numberposts' => -1
    );

Basically I want to pull all posts that have a meta start_date greater than today’s date and order by these dates.

As a side note – can you do a meta_query search on say location key and still orderby date key?

This is the first time I’ve ever tried ordering by meta, and have found some good posts but still cannot wrap my head around it.

Related posts

Leave a Reply

1 comment

  1. OK, I figured this out as my post lead me to another good example. The commented out meta_query is date greater than today. The other is using a different key. Both work!

        $today = date("Ymd");
        
        $args = array(
            'post_type' => 'uppy_events',
            'post_status' => 'publish',
            'meta_key' => 'event_date', 
            'orderby'       => 'meta_value_num',
            'order'         => 'ASC',
            'meta_query' => array(
                /* array(
                    'key' => 'event_date',
                    'value' => $today,
                    'compare' => '>='
                ) */
                array(
                    'key' => 'event_location',
                    'value' => 'vancouver',
                    'compare' => '='
                )
            ),
            'numberposts' => -1
        );