WordPress.org

Ready to get started?Download WordPress

Forums

Help with custom query with custom fields (2 posts)

  1. noworyz
    Member
    Posted 2 years ago #

    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

    <?php
         $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(
    		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

  2. bcworkz
    Member
    Posted 2 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags