Show Most Viewed Post And Show View Count (For Custom Themes)

Published On Thursday June 4, 2020 Reading Time: < 1 minute

Mostly on news template we need to show most views list of posts and yes there are plenty of plugins to do so but if you are doing a custom theme on your own we can also do the same thing using some simple codes. So, here you can see how to achieve the most viewed posts.

So we need to tweak 2 pages for obtaining it first the function.php file and another the single.php file where the full content is displayed.

Function.php Page

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

Now once done add the following code in single.php file. Better to place it right after get_header function call.

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

Now for the implementation, we can take a loop

<?php query_posts('meta_key=post_views_count&posts_per_page=3&orderby=meta_value_num&order=DESC'); 
if (have_posts()) : 
while (have_posts()) : the_post(); ?> 
<a href="<?php the_permalink($post->ID); ?>"><?php echo get_the_title($post->ID); ?></a>
<img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>>
<?php the_content(); ?>
<?php endwhile; endif; wp_reset_query(); ?>

Now, to show the count of the post that it is read for in the post details page. Just need to place the code in single page where you want display the times the post is count.

<?php echo getPostViews(get_the_ID());?>
0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x