How to Display Most Popular Post Without Using Plugin in WordPress

There are numerous plugins available on the WordPress plugin directory for most popular posts. We are going to display the most popular post using the simple post query based on post views. We will be using post Meta to store the views count and we’ll fetch the posts according to the views count using the stored Meta value. Sounds confusing but it’s easier to implement.

It’s not that hard. Adding a few lines of code on functions.php and modifying our template file will be enough.

Display Most Popular Post Without Using Plugin


Step 1: Set post views count using post meta

Add the below code in your current theme’s functions.php.

functions.php

function pp_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 pp_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);
 }
}

Step 2: Displaying the Popular Post

Add the below code in your template file where you want to display the most popular post. For example, single.php or home.php.

single.php

<ul>
  <?php
   global $post;
   $args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
   $myposts = get_posts( $args );
   foreach( $myposts as $post ) : setup_postdata($post); ?>
     <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
     <li><?php pp_setPostViews(get_the_ID()); echo pp_getPostViews(get_the_ID());; ?></li>
   <?php endforeach; ?>
</ul>