Show Popular Posts in WordPress

One of many effective ways to keep website visitors engaged is by showing them trending content on the website. Learn how to display popular posts in WordPress without any plugin.

Show Popular Posts in WordPress

Popular posts are those posts with the most traffic, comments or social shares. Highlighting the best content of the website helps in keeping users engaged, which increases the page views and lowers the bounce rate. In this post, we will learn how to show popular posts in WordPress without using a plugin.

 

Display Popular Posts Using Custom Code

We will display popular posts by page views, but WordPress does not store the page views anywhere in the database, so first we need to save the page views. We will save post meta with the key post_view_counts on each page visit using the following function. Add the following code to the active theme's functions.php file.

// Track post views
function set_post_views($post_id) {
$count_key = 'post_views_count';

$count = get_post_meta($post_id, $count_key, true);

update_post_meta($post_id, $count_key, intval($count));
}

This function will increment the page view count each time it is called. Now this function can be called in single.php or any single page of a custom post like this:

<?php set_post_views(get_the_id()); ?>

The following snippet will fetch the posts by the post_views_count meta key. This code can be moved to another custom function as needed. The following is the breakdown of code:

  • Prepare a new WP_Query with the arguments posts_per_page for the number of posts we need.
  • The meta_key is the key of the post meta post_views_count, which we updated above.
  • The next parameter orderby, will sort the posts by meta key value, treating it as a number.
  • The order key DESC will show the posts with the most views on top.
<?php
// Get popular posts by post_views_count meta key
$popular_posts = new WP_Query([
'posts_per_page' => 5,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
]);

while ($popular_posts->have_posts()) : $popular_posts->the_post(); ?>
<ul class="popular-post">
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
</ul>
<?php endwhile; wp_reset_postdata(); ?>

We demonstrated a simple and easy way to show WordPress popular posts with example code. Using the WP popular posts is a smart way to increase page views, decrease bounce and keep users engaged.