1

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.

<?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?

2
  • How is the date stored? YYYY-MM-DD? Timestamp?
    – vancoder
    Mar 18, 2013 at 19:33
  • It's YYYY-MM-DD
    – timshutes
    Mar 19, 2013 at 0:03

1 Answer 1

4

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.

2
  • thanks this worked perfectly! I knew meta_query was the answer, just missed on the date format. Thanks!
    – timshutes
    Mar 19, 2013 at 4:16
  • type => DATE is the magic. Not found in so many websites. Thanks @vancoder
    – Khom Nazid
    Apr 11, 2022 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.