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.
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.