admin管理员组

文章数量:1122832

I have a custom post type that is simply titles with a date field. I want to display these posts in a list in order of this date field (not date posted). So simply:

--

Sample date

Event title 1
Event title 2

Sample date

Event title 3
Event title 4
Event title 5

(etc)

--

No extra info, that's literally all I want to display.

I can't figure out how to go about this at all. I'm not great at PHP so I'd appreciate any help with this.

I have a custom post type that is simply titles with a date field. I want to display these posts in a list in order of this date field (not date posted). So simply:

--

Sample date

Event title 1
Event title 2

Sample date

Event title 3
Event title 4
Event title 5

(etc)

--

No extra info, that's literally all I want to display.

I can't figure out how to go about this at all. I'm not great at PHP so I'd appreciate any help with this.

Share Improve this question asked Sep 4, 2013 at 21:20 user1473358user1473358 311 silver badge4 bronze badges 1
  • Was this ever resolved? If so, please accept the answer if that helped, or add and accept your own answer telling us how you solved this. Thanks. – Andy Macaulay-Brook Commented Aug 8, 2016 at 19:44
Add a comment  | 

2 Answers 2

Reset to default 0

I solved the same problem like this First you store each posts in another array called $events_by_date with date as the index. If another event post falls in the same date you put that post under the same index.

Please comment if you need further explanation.

  <?php
//setup your wp_query parmeters to make the query

$calendar_results   =   new WP_Query( $wp_query_params );

$events_by_date = array();


     while ( $calendar_results->have_posts() ) : $calendar_results->the_post(); 
        //$date_group =  strtotime($calendar_results->post->post_date);
        $date_group = strtotime(date('Y-m-d',$date_group));
        $events_by_date[$date_group][] = $calendar_results->post;
    endwhile;

global $post;


foreach($events_by_date as $date_heading=>$rows) {

    echo '<h2 class="published-date">',
            ucfirst( strftime( '%A %d %b',$date_heading ) ) ,
    '</h2>';

    foreach ($rows as $post ) {
        setup_postdata($post) ;
        get_template_part( 'content', $template ); 
    }


}   

wp_reset_query();

Just use WP_Query like this:

$posts_by_date_field = new WP_Query(array(
    'post_type'         => 'POST_TYPE_NAME',
    'posts_per_page'    => -1,
    'meta_key'          => 'FIELD_NAME',
    'orderby'           => 'meta_value',
    'order'             => 'DESC'
));


if ($posts_by_date_field->have_posts()) : while ($posts_by_date_field->have_posts()) : $posts_by_date_field->the_post();

    // LOOP

endwhile; endif;

本文标签: orderDisplay custom post types by date field