I'm using the following code to list all years from my blog, I guess we can call it an archive.
<?php
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts ORDER BY post_date DESC");
foreach($years as $year) : ?>
<?php echo $year ?>
<?php endforeach; ?>
What I'd like to achieve though is to also display, in front of each year, the number of posts (count) that each year has. Example:
2015 (5 posts)
2014 (3 posts)
2011 (10 posts)
I found a hint somewhere and tried to implement it, but didn't work. Here's what I was trying:
<?php
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts ORDER BY post_date DESC");
$count = $years->post_count;
foreach($years as $year) : ?>
<?php echo $year ?> (<?php echo $count ?> posts)
<?php endforeach; ?>
Any ideas?
Thank you.
EDIT @David
<?php
/** Grab the years that contain published posts, and a count of how many */
$query = $wpdb->prepare('
SELECT YEAR(%1$s.post_date) AS `year`, count(%1$s.ID) as `posts`
FROM %1$s
WHERE %1$s.post_type IN ("post")
AND %1$s.post_status IN ("publish")
GROUP BY YEAR(%1$s.post_date)
ORDER BY %1$s.post_date DESC',
$wpdb->posts
);
$results = $wpdb->get_results($query);
/** Create the '$years' array, a list of all yearly archives */
$years = array();
if(!empty($results)) : foreach($results as $result) :
$url = get_year_link($result->year); // The archive link URL for the current year
$text = $result->year; // The archive link text for the current year
$count = $result->posts; // The number of posts in the current year
$years[] = get_archives_link($url, $text, 'html', '', $count); // Create the archive link for the current year
endforeach;
endif;
?>
<a href="<?php echo $url; ?>"><li><?php echo $text ?> <span class="lower">(<?php echo $count ?>)</span></li></a>
$years
query, which wont work.