Adding a list of popular posts to your website is a great way to increase user engagement on your site. It shows your readers what people are reading and interacting with the most – which in turn should encourage people to browse around your website more.
There are lots of posts across the blogosphere describing how to do this. Some look at the number of comments, and others track the page views, but they are all quite complex and cumbersome.
I even developed a system for looking at the most popular posts based upon comment count, with a date limit to keep things recent, and it worked (you can still see it in action on the homepage carousel), but wasn’t perfect.
Then today I had a brain(fart)wave.
I have used the WordPress stats plugin for a while and it displays a nice little list of the most popular posts on the WordPress Dashboard… and I got to thinking – “why don’t I use that list myself?”
My first stop was the plugin code – and 5 minutes later I had found a very simple couple of lines of code that would grab the most popular posts using the stats api.
5 minutes after that I had written the following code, and added it to the #footer of this very site (it’s in the right hand column labelled “Currently Hot”).
<?php
if (function_exists('stats_get_csv')) {
$top_posts = stats_get_csv ('postviews', 'days=7&limit=8');
if (count($top_posts) > 0) {
echo '<ol>';
foreach ($top_posts as $p) {
?>
<li><a href="<?php echo $p['post_permalink']; ?>"><?php echo $p['post_title']; ?></a></li>
<?php
}
echo '</ol>';
}
}
?>
This code works really well, the stats are accurate, and it even has built in database caching. What’s not to like?
Note: The WordPress stats plugin, fully enabled, is a requirement for this to work.
Oh – and if you want the 1 line version check below. Personally I prefer the slightly longer version above.
<?php foreach ($top_posts = stats_get_csv ('postviews', 'days=7&limit=8') as $p) { ?><a href="<?php echo $p['post_permalink']; ?>"><?php echo $p['post_title']; ?></a><?php } ?>
Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).
Link to this page
Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.