Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Group post by year and then sort alphabetically WordPress

  • SOLVED

I need to group post by year and then sort them alphabetically like
2016
post1
post2
....

2015
post1
post2
post3

2014
post1
....

Answers (1)

2016-02-26

Arnav Joy answers:

you can try following

<?php

global $wpdb;
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type= 'post' ORDER BY post_date DESC");
if( $years ){
foreach( $years as $year ){
echo '<div class="clearfix">';
echo "<h2 class='year clearfix'>" . $year . "</h2>";

$conn_arr = array();

$query = new WP_Query( array(
'posts_per_page' => '-1',
'post_type' => 'post',
'year' => $year
) );

if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
the_title();
echo '<br>';
endwhile;
endif;
}
}