Upcoming Event: How do I sort database by custom date field, but ignore past dates?

I am using an events plugin and struggling to get my database query to be perfect. The query is on the event-single.php template. What I need the query to do:

  • Query the “events” custom post type for upcoming events
  • Sort by _event_start_date meta_key to show earliest date (nearest event)
  • Not display PAST events
  • If “current event”, show next nearest event

Here’s my current $args.

Read More
<?php $args = array(
    'post__not_in' => array($donotrepeat),
    "post_type" => 'event',
    'meta_key' => '_event_start_date', // name of custom field
    'orderby' => 'meta_value_num',
    "order" => 'ASC',
    "posts_per_page" => 1
   );
?>

Defining $donotrepeat earlier

$donotrepeat = get_the_ID();

So far, the query successfully

  • Queries custom post type
  • Ignores the “current” event
  • Sorts by earliest date.

I cannot figure out how to ignore ‘past’ dates though. There is another meta key ‘scope’ created by this plugin that contains values like ‘past’ and ‘future’ – so that could be promising.

I’ve tried using meta_query to sort through the past date issue, but I just can’t seem to get it to work. I think this is probably the way to go, but I’m open to other ideas. I’m sure this isn’t THAT difficult… can anyone help?

Related posts

Leave a Reply

1 comment

  1. You’re pretty close, but I wouldn’t be distracted by the ‘scope’ meta key. The following is untested.

    <?php
    $args = array(
        'post__not_in' => array($donotrepeat),
        "post_type" => 'event',
        'meta_key' => '_event_start_date', // name of custom field
        'orderby' => 'meta_value',
        "order" => 'ASC',
        "posts_per_page" => 1,
        'meta_query' => array(
            array(
                'key' => '_event_start_date',
                'value' => date('Y-m-d'),
                'compare' => '>=',
                'type' => 'DATE'
            )
        ),
    );
    ?>
    

    The meta_key is only present for ordering – meta_query controls the actual selection.

    Note that I left your posts_per_page as is, even though it will limit the selection to one record.