• March 20, 2018
  • Development

WordPress: Query Custom Posts Types by Date

One of the common queries we run into when pulling custom post types is sorting them by a custom post meta date.  Using a meta_query we can not only sort by date, but also only pull posts from a certain time frame.  One place we use these frequently is pulling upcoming events or perhaps a sale item that we only want to show for a specified amount of time.

<?php
global $post;
$today = date('Ymd');
$args = array (
  'post_type' => 'custom_post_type',
  'posts_per_page' => -1,
  'meta_key' => 'meta_date',
  'orderby' => 'meta_value',
  'order' => 'ASC',
  'meta_query' => array (
    array (
      'key' => 'meta_date',
      'value' => $today,
      'compare' => '>=',
    )
  ),
);
$posts = get_posts( $args );
if( $posts ) :
  foreach( $posts as $post ) : setup_postdata( $post );
    // Get information for posts here...
  endforeach;
endif;
wp_reset_query();
?>

A couple of things to point out here that will make this work.  First, make sure that your date format in your meta data is able to be added and subtracted.  For example, 20180101 for January 01, 2018 can be easily calculated or a Unix Timestamp in this example would be 1514764800.  This will allow the database to compare the dates.  Whatever format you are using, $today needs to be set to the same format.