I have a worpresss 4.0.12 website; i created a custom template category-$id.php in which I have to show post ordering them by Year DESC and by month ASC (or a custom field ASC), the result should be something like this:
2017
- Post 10-01-2017
- Post 25-01-2017
- Post 05-03-2017
- Post 06-12-2017
2016
- Post 10-01-2016
- Post 05-03-2016
- Post 06-12-2016
2015
[…]
How can I do?
I Tried width query_posts($args) but I can’t order by a second field
1 Answer
To show a list by Year DESC and by month ASC:
change your post type with custom_post.
global $wpdb;
$posts = $wpdb->posts;
$sql = "SELECT DISTINCT(YEAR(`post_date`)) as years FROM $posts WHERE post_type="custom_post" ORDER BY years DESC"; //Get all post year list by DESC
$result = $wpdb->get_results($sql);
foreach($result as $rs) {
echo '<h2>'.$rs->years.'</h2>';
$args = array(
'post_type' => 'custom_post',
'post_per_page'=> -1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'ASC',
'date_query' => array(array(
'year'=> $rs->years,
),),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
echo '<a href="'.get_permalink().'">'.get_the_date().'</a>';
endwhile;
}
}