Query date in wordpress loop

You want to query for posts with event_date in the future but you have saved (or so it seems from a comment), your dates as:

date("F", $unixtime)." ".date("d", $unixtime).", ".date("Y", $unixtime);

That is “textual month name” + “numeric day” + “numeric year”. There is no way to query/sort that format so that it matches a calendar. Your sorting options are “alphabetical”, which is obviously going to be wrong, or “numerical”, which is also obviously wrong. The only human readable date format that sorts in a way that matches a calendar is “numeric year” + “numeric month” + “numeric day”, or “YYYY-MM-DD”. The choice of separator is arbitrary and can be nothing. That is date('Y-m-d'). If your dates were stored in a rational format a query like the following should do what you need:

$args = array(
    'post_type' => 'events',
    'orderby'   => 'event_date',
    'meta_key'  => 'event_date',
    'order'     => 'ASC',
    'meta_query' => array(
      array(
        'key' => 'event_date',
        'value' => date('Y-m-d',time()),
        'compare' => '>'
      )
    ),
);
$q = new WP_Query($args);
var_dump($q->request);

You can always just store a Unix timestamp as well. Those sort matching calendar order as well. You would then format the date on display. This is my preference with dates unless you are saving to “date” format column in a MySQL table. If you save as a timestamp, use:

'value' => strtotime('today'),

instead of:

'value' => date('Y-m-d',time()),

Leave a Comment