1

How can I separate posts by year in archive page for Custom Post Type?

while ( have_posts() ) : the_post();

the_title();
the_post_thumbnail('thumb'); 

endwhile;

The end result would look something like this:

2016
- Title1
- Title2
- Title3
- Title4

2015
- Title1
- Title2
- Title3
- Title4

etc.
1

1 Answer 1

8

This little snippet could help you.

$years = array();

  if( have_posts() ) {
    while( have_posts() ) {
      the_post();
      $year = get_the_date( 'Y' );
      if ( ! isset( $years[ $year ] ) ) $years[ $year ] = array();
      $years[ $year ][] = array( 'title' => get_the_title(), 'permalink' => get_the_permalink() );
    }
  }

This code gets all posts (in the current loop), gets the year of each post, pushes each post title and permalink to its year array.

3
  • 3
    There is no need for secondary query we can do it using primary loop also
    – bravokeyl
    Jul 11, 2016 at 12:15
  • @bravokeyl It's an snippet, the benefit of using an separate query is that you can use this code everywhere, even in admin pages.
    – Ehsaan
    Jul 11, 2016 at 12:16
  • @PieterGoosen Changed to loop.
    – Ehsaan
    Jul 11, 2016 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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