I’m looking to echo the number of posts per month since the blog began, and for months where there was no posts echo ‘0’.
This is the output I want:
January 1, February 3, March 8, April 3, …
Any help would be great.
Dave
I’m looking to echo the number of posts per month since the blog began, and for months where there was no posts echo ‘0’.
This is the output I want:
January 1, February 3, March 8, April 3, …
Any help would be great.
Dave
You must be logged in to post a comment.
So basically what you need to do is paste the following code in your themeâs sidebar.php file or any other file where you want to display custom WordPress archives.
Note: If you want to change the number of months displayed, then you need to change line 19 where the current $limit value is set to 18.
Our CSS looked a bit like this:
Now if you want to show the count of posts in each month, then you would need to add this bit of code anywhere in between line 12 â 16 of the above code:
Your best bet is probably to use
$wpdb
directly. You can useCOUNT
andGROUP BY
to make things easier.A query might look something like this:
That gets you most of the way there. Be sure to have a look at the generic results section of the
wpdb
docs.To get you the rest of the way there, you’ll likely want to loop through a range of 1-12, creating month names and checking to see if the results include that month.
Here’s an example implemented as a shortcode:
The
foreach
loop at the end is the one to pay attention to. Loop through a 1-12 range, create a proper month name for each, and see if the post count exists. If it does use that number, or else print 0.That shortcode as a plugin.
EDIT Display counts for the last 12 months.
This one requires a bit more complex query, but the concept is the same: get post counts, group by month. This time, order by post date ascending. From there we just need to make an array of month numbers based on the current date.
Example (again as a shortcode)
Thanks for your help, Chris and Varun. I seem to have done it by mostly using Chris’s example, and taking a little code from Varuns too.
Here’s what I ended up with. I’m not sure if it’s the most efficient way of doing this, its more a proof of concept for me but if anyone has a way to do it any cleaner then please let me know.
Thanks all.