Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

This question follows on from: Can you do a date comparison on a custom field and query two or more custom taxonomies using WP_Query?

and a similar thing here: http://stackoverflow.com/questions/7080352/multiple-custom-fields-stored-as-meta-keys-how-to-connect-with-the-post/

I'm trying to compare a start and end date which are custom fields in a post type of exhibitions which is set up using a jquery date picker with dateFormat : 'dd-mm-yy'

$today = date('Y-m-d', strtotime('-6 hours'));      
$args = array(
    'showposts' => 1,
    'orderby' => rand,
    'post_type' => 'exhibition',
    'meta_query' => array(
        relation' => 'AND',
        array(
        'key' => 'startDate',
        'type' => 'CHAR',
        'value' => $today,
        'compare' => '>='
         ),
        array(
        'key' => 'endDate',
            'type' => 'CHAR',
            'value' => $today,
            'compare' => '<='
             ),
   )
);

What I don't understand is how this is being saved into the meta data - presumably it will be type CHAR and why my query doesn't seem to work correctly

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

This:

date( 'Y-m-d', strtotime('-6 hours') );

Is going to spit out something like 2011-11-11

If your date picker is using the format dd-mm-yy, then comparing the two is not going to work. dd-mm-yy, if it's what's in the field on post save/update, is what's going to be saved as the meta_value.

The meta value is likely getting saved as a string, which is fine -- you can still do date comparisons, but the formats have to match. There are a few options for solving this:

  1. Convert your dates to unix time stamps before saving them in the database -- use strtotime -- do the reverse on the front end: date( 'F, j Y', $some_time_saved_in_db ); to show the dates to users. Comparing timestamps should be the most reliable.
  2. Save your field with the ISO standard date format, YYYYMMDD, which works fairly well for comparing/sorting dates.
share|improve this answer
1  
Hi Christopher, thanks for that - absolutely resolved the problem using your second suggestion! –  darren Nov 11 '11 at 15:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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