• Resolved Klimseven

    (@klimseven)


    I’m trying to get all of the posts from a custom post type (‘match’), and display them in order of a custom date field (date_field – using the date picker from the Advanced Custom Fields plugin). This seemed to be working fine initially, but not anymore. Infact, sometimes it works, and sometimes it doesn’t. Mostly it seems to order the posts randomely. It’s odd and I can’t figure out what the problem is.

    Can anyone see anything wrong with this code?

    <?php
    		$the_query = new WP_Query( array(
    				'post_type' => 'match',
    				'order' => 'ASC',
    				'orderby' => 'meta_value',
    				'meta_key' => 'date_field'
    				) );
    				$current_header = '';
    
    				while ( $the_query->have_posts() ) :
    				$the_query->the_post();
    
    				# get the datum for this post
    				$temp_date = get_post_meta( get_the_ID(), 'date_field', true );
    
    				if (strtotime($temp_date) > strtotime('now')){
    
    					if ( $temp_date != $current_header  ) {
    					$current_header = $temp_date;
    					echo "<dt>$current_header</dt>";
    					}?>
    
    				<dd><?php the_title();?></dd>
    
    		<?php } endwhile; wp_reset_query();?>
Viewing 4 replies - 1 through 4 (of 4 total)
  • The first question is “What is the format of the date_field values”. In order to sort properly, the year must be first, followed by the month and then the day.

    Thread Starter Klimseven

    (@klimseven)

    Thanks for your reply. So if I have this order in the database, how can I make the outputted date more user friendly?

    You did not say what the ‘user friendly’ format is, so I assume this format ‘September 15, 2013’. Try changing this:

    if ( $temp_date != $current_header  ) {
       $current_header = $temp_date;
       echo "<dt>$current_header</dt>";
    }?>

    to this:

    if ( $temp_date != $current_header  ) {
       $current_header = $temp_date;
       $display_date = date('F j, Y', strtotime($temp_date));
       echo "<dt>$display_date</dt>";
    }?>
    Thread Starter Klimseven

    (@klimseven)

    Perfect. Thanks for your help!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘orderby custom post type by date field not working’ is closed to new replies.