Adding A Popular Posts Section To Your WordPress Blog

Reading Time: 4 minutes

Now that my blog has started to get a decent amount of content I wanted to add a way to keep my most viewed posts at the top, since, you know, I’m not allergic to pageviews. Stupid jokes aside, it’s good practice to keep your most popular posts fresh on your site so people can get to the information they find most useful. It also allows the user to show you what content they find most useful, and keep that content from getting buried.

Now where to start? This is WordPress so you could always go for the plugin route. Check out WPMU for some options on that front. That’s no fun. Besides how are you going to learn anything if you don’t completely crash the site with a misplaced semi-colon in your functions.php file? (Note: You should probably test this on a local site or test server first.)

The second one sounds fun. Let’s try that.

First off these two snippets form WP Snipp are really all you need (Track Posts Views Without a Plugin Using Post Meta and Most Popular Posts Using Views Post Meta). So if you’re in a hurry and don’t care how it works just go grab the code from there. I’m going to try to explain what’s going on a little bit.

The first thing we need to do is create the functions that are going to get and set our post views as custom meta in each individual post. So we’ll grab the snippet form the first WP Snipp link and insert that into the functions.php file of our theme.

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

That may look pretty crazy, but it’s pretty simple. The first function (getPostViews) is a way of getting the number of views a post currently has and returning that number. What it does is store the meta $key into the variable $count_key so we can easily reference it in the get_post_meta function call on the next line. For more on get_post_meta check out the WordPress Codex.

Next we create the $count variable and store the value of the meta field “post_views_count” into that variable. So if our post has been viewed 35 times $count = 35.

Line 3 inside the function starts an if statement to check it count has a value yet or not. If count does not have a value it sets it to 0 and returns 0 views. Essentially creating the “post_views_count” meta field if it doesn’t already exist. Otherwise it just returns $count in a string, or in our above hypothetical “35 Views”.

That function was easy enough, but didn’t show us how we set the post views. You’ll notice the code for our second function is almost the same as the last. It starts off the same with the first difference being in the if of our if else statement. In this function if our $count doesn’t have  value yet we set it to 0. Which we could probably set as 1 honestly since the post has to be viewed at least once just to have this function run, but I’ll leave it at 0 for now. We also don’t return the value at the end of our if, well, because there’s no reason to.

So if our post doesn’t have any value in its “posts_view_count” custom meta filed we return 0 views. But what if it has a value. That’s where our else comes in. If we’ve got the 35 views from above and someone views the post, calling our setPostViews function we take the 35 from $count and add 1 ($count++) then update the post meta with that new value. Check out more on update_post_meta at the Codex.

That’s cool and all, but now we just have functions that are never actually called. So what are we going to do? Call them! How? With this!

<?php setPostViews(get_the_ID()); ?>

Where do we put it? In our single.php file within the loop! I put mine right after the loop call, why? Because I can. And to make sure it gets called when the post gets viewed. So we called setPostViews and passed it get_the_ID so it goes to the correct post.

Now we need a way to see that view count number. To do that we simply echo the value that getPostViews returns.

<?php echo getPostViews(get_the_ID()); ?>

Drop that within your theme wherever you want to display the number of views for a particular post.

Of course to get the best value you’re going to want to display a list of your most popular posts. In order to do that we just need to query the posts by our view_posts_count custom meta field.

<?php 
		$popular_query = new WP_Query('meta_key=post_views_count&orderby=meta_value_num&order=DESC&showposts=3');
		while ($popular_query->have_posts()) : $popular_query->the_post();
	?>

// Your code goes here

<?php endwhile; ?>

Now just insert your code within that space, and you’ve got yourself a list of your popular posts.

If you’re having trouble, here’s an example ripped straight from my sidebar.php file that’ll give you a nice <ul> of your posts.

<ul>
	<?php 
		$popular_query = new WP_Query('meta_key=post_views_count&orderby=meta_value_num&order=DESC&showposts=3');
		while ($popular_query->have_posts()) : $popular_query->the_post();
	?>

			<li class="popular-post">
				<?php if(has_post_thumbnail()) :?>
				<div class="popular-thumb thumbnail"><?php the_post_thumbnail('popular-thumb'); ?></div>
				<?php else :?>
			    <?php endif;?>
				<div class="popular-title">
					<h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
					<p class="post-views"><?php echo getPostViews(get_the_ID()); ?></p>
				</div>
			</li>

	<?php endwhile; ?>
				</ul>

That’s it. Have fun with your shiny new WordPress popular posts. In the future I plan to add a way to make this time sensitive so we only show posts from the last 30 days or so. Stay tuned.

Pin It on Pinterest