Displaying Event within two given time frames

Querying on the meta data table is slow, and as since it’s also used for general data, you need to be careful about your date format if you’re storing dates there. For instance, with dmY format:

  • 01112014 ( 1st November 2014 )
  • 11012014 ( 11th January 2014 )
  • 12052014 ( 12th May 2014 )

is ‘correct’ in that the numbers are sorted correctly, but gives you an incorrect order chronologically speaking (which is usually what you want with events).

So if you are using postmeta, you must use either the timestamp or Ymd format. Assuming that, then you can get the ‘next’ event:

$args = array(
    'post_type' => 'event',
    'posts_per_page' => 1,
    'meta_query' => array(
        array(
            'key'     => 'date', //or whatever key you're using
            'value'   => date_i18n( 'Ymd' ),
            'compare' => '>='
        )
    ),
    'orderby' => 'meta_value',
    'meta_key' => 'date', //or whatever key you're using
    'order'   => 'asc',
);

$events = get_posts( $args );
if( $events ){
   $next_event = array_pop( $events );
}else{
   //no event found
}

That said, it’s best to avoid post metadata (for performance concerns – it’s even worse for recurring events if you ever need that). Additionally, there is a hoard of different event management plug-ins (I’ve built: Event Organiser) which not only handle all this for you, but provide a UI for the user rather than using custom fields.

With Event Organiser you can get the next event with:

$events = eo_get_events( array(
    'event_start_after' => 'now',
    'posts_per_page'    => 1
));
if( $events ){
   $next_event = array_pop( $events );
}