How to Display Popular Posts in WordPress Without a Plugin
This tutorial will show you a simple way to display the most popular posts by views without using any plugin. In this article, we will show you how to track and display popular posts WordPress without using any plugins.
Open the functions.php file the following code :
setPopulerViewsPosts() function and post meta with post_views_count meta key.
functions.php
function setPopulerViewsPosts($postID) {
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if($count=='') {
$count = 0;
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '0');
} else {
$count++;
update_post_meta($postID, $countKey, $count);
}
}
Open the single file. like content.php or single.php and place the setPopulerViewsPosts() function inside the loop.
setPostViews(get_the_ID());
Display the Most Viewed Posts
The following query will fetch the posts based on the post_views_count meta key value.
<h1>Most popular posts</h1>
<?php phpquery_posts('post_type=post&post_status=publish&meta_key=post_views_count&orderby=meta_value_num&order=DESC&posts_per_page=6');
if (have_posts()) : ?>
<ul>
<?php while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif;
wp_reset_query(); ?>
Watch live demo of our live site on right sidebar under MOST POPULAR POSTS section.