Support » Plugins » Hacks » Help with custom query with custom fields

  • I have a query to grab certain posts based on a custom field (a date). The query is supposed to display posts with the custom field date in the future. The problem is that the custom field is stored as m/d/Y rather than Y/m/d. This is an issue when comparing dates because it doesn’t use the year to base if it is in the future or not.

    So, what I need to do, is to somehow read the custom field, change the format and then compare the dates.

    My current query

         $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
         $today = date('Y/m/d', strtotime('-6 hours'));
         $myquery = new WP_Query(array(
         'post_type' => 'itineraries',
         'posts_per_page' => 20,
         'paged' => $paged,
    	 'meta_key' => 'start_date',
         'orderby' => 'meta_value',
         'order' => 'ASC',
         'tax_query' => array(
    			'taxonomy' => 'regions',
    			'field' => 'slug',
    			'terms' => 'future'
        if ($myquery->have_posts()) :
        while ($myquery->have_posts()) : $myquery->the_post();

    So above, I need to convert the meta_key start_date to the Y/m/d format for better comparison. How do I do this using code?

    I did some research and implode(‘-’, array_reverse(explode(‘/’,$date))); seems like it might be helpful but I’m not sure how to incorporate it in.

    Thanks for any help

Viewing 1 replies (of 1 total)
  • Moderator bcworkz


    You can create DateTime objects from the Y/m/d format and diff them.

    I prefer to use Unix timestamps. (seconds since Unix epoch, 00:00:00 UTC on 1 January 1970) Simply use strtotime() on what ever date format string you have to get the proper timestamp returned. To eliminate ambiguity of numbered dates, always use slash separator for m/d/y and dash or dot separator d-m-y. Convert your dates to timestamps, then compare those.

    In case it’s not too late for your field format, you could actually directly query dates stored as timestamps, but not when stored as strings. Then you don’t have to query all the posts to check the dates, rather just query for the desired timestamp range.

Viewing 1 replies (of 1 total)
  • The topic ‘Help with custom query with custom fields’ is closed to new replies.