Take the 2-minute tour ×

I have a custom post type for a cycling club uses to schedule rides. There is a custom field for these posts where the user selects the "ride date" with JQUI date & time picker. This information is stored as such in postmeta:

07/26/2012 @ 12:00 am

I query these posts with:

query_posts(array('posts_per_page' => 3, 'post_type' => 'rides');

But we don't want rides that already happened to display:

    //Format User entered ride date
$date = get_post_meta($post->ID, 'date', true);
$date = str_replace(' @ ', ' ', $date);

//adjust unix timestamp
$time = time() -21600;

//If ride has not already happened, print it.
if ( $time < strtotime( $date ) ):

That sort of works, but there is a fundamental flaw that a more seasoned PHP dev will likely see almost immediately. In my query I'm fetching the last three posts based on POST DATE and then testing the meta value to see if the rides already happened or not. What I really need to do is take a step back and test wether a ride has already happened in my query.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

I would suggest storing the date-times as either:

  • Timestamp (to sort/compare by meta_value_num)
  • 'yyyy-mm-dd hh:mm (e.g. 2012-04-11 19:37) to sort/compare by meta_value

Then the following will work (assuming you're using timestamp):

$now = current_time('timestamp');
$args = array(
    'post_type' => 'rides',
    'posts_per_page' => 3,
    'meta_query' => array(
            'key' => 'date',
            'value' => $now,
            'compare' => '>'
//This breaks pagination!

See Codex on WP_Query.

For bonus points: don't use query_posts! (See this). It's inefficient and requires some extra work to get pagination etc to work.

I suggest you see this (very) related post which shows you how to use the pre_get_posts hook instead. That post also includes how to sort by your custom 'date' field.

share|improve this answer
Thanks, this with meta_compare did the trick. –  Justin W Hall Apr 12 '12 at 1:59

Your Answer


