I am trying to display data from a custom post type, based on the date that the event will occur. The date is set in a meta box in the cpt.

My code so far is:

$today = date('d/m/Y');
$p_date = get_post_meta($post->ID, '_cmb_training_date', true);
$p_date2 = get_post_meta($post->ID, '_cmb_training_start_date', true);
if($p_date > $today) {
 // stuff

This works fine (only shows events after todays date) but I want to add in another event type ($p_date2) as well but if I do:

if($p_date > $today || $p_date2 > $today) {
 // stuff

It displays all the posts from the CPT

The date formats are all the same, so it's got to be with my if statement

any ideas?

  • 3
    I don't think you can compare date strings formatted that way. Try using YYYYMMDD as an integer or, my favorite, Unix timestamps.
    – GhostToast
    Commented Jun 10, 2013 at 13:38
  • Your date format is not going to sort correctly. I suspect that is the problem. It certainly is a big problem. See: wordpress.stackexchange.com/a/78048/21376 Also: wordpress.stackexchange.com/a/91163/21376
    – s_ha_dum
    Commented Jun 10, 2013 at 13:41
  • perfect guys, works as intended now :) one small thing, is it possible to grab just the month from the date e.g. if mm = xx then display, as would like to try and display on a monthly list? Commented Jun 10, 2013 at 14:15

2 Answers 2


For date manipulations you should use the DateTime class. Also, dates should be stored in Y-m-d format (if you're storing them differently you can create the DateTime object from a specified format: http://php.net/manual/en/function.date-create-from-format.php (php 5.3+) - but I recommend storing it in the unambiguous Y-m-d format ).

The following assumes Y-m-d formatin the post meta:

$today = new DateTime( 'now' );
$p_date = new DateTime( get_post_meta($post->ID, '_cmb_training_date', true) );
$p_date2 = new DateTime( get_post_meta($post->ID, '_cmb_training_start_date', true) );

if( $p_date > $today || $p_date2 > $today) {
   // stuff

As you mention in the comments. You can also easily obtain year/monthy/day information:

if( $p_date2->format('m') == '01' ){
      //$p_date2 is in January

As far as date comparisons go, I think a general good practise would be to convert your times to strtotime. Especically if there is a change of those dates being user-inputted, it's best to have them all at the same level.

I have a post here that goes into it a little.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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