How to Add Upcoming Events and Events Archive with Custom Post Types

Recently, I had an opportunity to build an events listing that showed only upcoming events, with the next event appearing at the top. That’s pretty easy to accomplish. But I also wanted past events to disappear from the listing and show up instead on an events archive listing. It took a lot of searching and asking questions in two WordPress forums to piece together a query that worked.

First, I created a custom post type for events. Then I created a custom field called “order-date” to control ordering. Why a custom field? Why not rely on WordPress’ innate order-by-date function? Because WordPress uses the date posted, and it’s quite likely that events will not be posted in the order of their occurrence. But just as important, I needed the order-date to be the date of the event so we could use it to drop an event from the upcoming events listing and move it to the events archive listing. The custom field uses the Y-m-d date format for comparison with the Y-m-d format of today’s date.

Here is the query on the upcoming events listing template:

<?php
   $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
      $today = date('Y-m-d'); //define “today” format
      query_posts(array(
      'post_type' => 'events', //query “events”
      'posts_per_page' => 5,
      'caller_get_posts' => 5,
      'paged' => $paged,
      'meta_key' => 'order-date',
      'orderby' => 'meta_value',
      'order' => 'ASC', //sort in ascending order
      'meta_query' => array(
         array(
         'key' => 'order-date',
         'meta-value' => $value, //value of “order-date” custom field
         'value' => $today, //value of “today”
         'compare' => '>=', //show events greater than or equal to today
         'type' => 'CHAR'
         )
      )
   ));
   if (have_posts()) :
   while (have_posts()) : the_post();
?>

On a separate template for displaying the archive listing, I made the following changes (highlighted in red) to display past events in descending order:

<?php
   $paged = ( get_query_var(&#39paged&#39) ) ? get_query_var(&#39paged&#39) : 1;
      $today = date(&#39Y-m-d&#39);
      query_posts(array(
      &#39post_type&#39 => &#39events&#39,
      &#39posts_per_page&#39 => 5,
      &#39caller_get_posts&#39 => 5,
      &#39paged&#39 => $paged,
      &#39meta_key&#39 => &#39order-date&#39,
      &#39orderby&#39 => &#39meta_value&#39,
      &#39order&#39 => &#39DESC&#39, //descending order
      &#39meta_query&#39 => array(
         array(
         &#39key&#39 => &#39order-date&#39,
         &#39meta-value&#39 => $value,
         &#39value&#39 => $today,
         &#39compare&#39 => &#39<>, //show events less than today (past)
         &#39type&#39 => &#39CHAR&#39
         )
      )
   ));
   if (have_posts()) :
   while (have_posts()) : the_post();
?>

Link to original post

Leave a Reply