I'm trying to display two different posts from my CPT named Events.

One is going to be the next event the other is going to be previous event.

I've got a metabox called 'Event date' The client at the moment places the date of the event in here.

I'm thinking of somehow using this date as a "breaker" if its written in D.M.Y format and that date has past then that event won't be displayed in next event, kind of like an expiration date.

So I would need to query the posts to the nearest date displayed in the metabox and display that post as the Next Event.

This is how the logic would work in my head, however I can't seem to find the correct stepping stone to start.

Sorry if this isn't very clear.


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(
            '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 );
   //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 );
| improve this answer | |
  • Thanks Stephen your plugin seems to solve all my issue's at first glance. Least I have a solution now and Know the direction to take in the future. – dannyw24 May 28 '14 at 9:43
  • Guess my only other question is how would I list the previous event closest to the current date. – dannyw24 May 28 '14 at 11:45
  • If you're going by start date, then just reverse the order (desc) and the compare in the meta query (<=) – Stephen Harris May 28 '14 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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