Beginner's Guide for WordPress / Start your WordPress Blog in minutes

How to Display Popular Posts by Views in WordPress (2 Ways)

Do you want to display popular posts by views in WordPress?

Displaying your popular posts can help you generate more traffic, keep visitors on your site longer, and build social proof.

In this article, we’ll show you how to display your popular posts by views in WordPress, both with and without a plugin.

How to display popular posts by views in WordPress (2 ways)

Why Display Popular Posts by Views in WordPress?

Sometimes it can be hard for your visitors to find your best content. Even your most popular articles can get lost when you have thousands of blog posts.

Displaying your most popular posts lets you show your most popular articles anywhere across your WordPress blog.

Your popular posts are the most successful pieces of content for a reason. By displaying these to your visitors, you’ll build trust, improve social proof, and ensure that your visitors stay on your website longer.

Popular posts example

When your visitors stay on your WordPress website longer, this gives you more time to convince them to make a purchase, join your email newsletter, or take another action.

With that said, let’s take a look at how to simply display popular posts by views in WordPress using 2 methods.

Click on the quick link to jump straight to your preferred method:

Video Tutorial

Subscribe to WPBeginner

If you’d prefer written instructions, just keep reading.

Method 1: Display Popular Posts by Views With a Plugin in WordPress

There are many WordPress popular posts plugins that you can use to display your most popular content, but the easiest plugin to use is MonsterInsights.

MonsterInsights is the best analytics solution for WordPress used by over 3 million websites. It lets you simply display your popular posts anywhere on your WordPress site.

Inline popular posts example

You can also use the Inline Popular Posts feature to show your popular posts directly within your content.

First thing you need to do is install the plugin. For more details, see our step by step guide on how to install Google Analytics in WordPress for beginners.

Note: there is a free version of MonsterInsights available, but we’ll be using the pro version since it includes the popular post feature.

Upon activation and set up, go to Insights » Popular Posts and then click the ‘Popular Posts Widget’ menu item.

Select popular posts widget

On this screen, you can select the popular post style you want to use. This will control the appearance of your popular posts.

There are a lot of additional customization options as well.

For example, under the ‘Theme Preview’ meta box, you can display your popular posts in a ‘Wide’ format below your content, or on the right hand side of your page with the ‘Narrow’ option.

Theme preview box MonsterInsights

Next, you can change the color and size of the post title, author, and date.

The ‘Widget-Layout Options’ menu will change the the number of columns that are displayed. There are additional display options you can customize on this screen as well.

MonsterInsights will automatically save all settings after you make a change.

Popular posts additional display settings

Once you’ve customized the appearance of your popular posts, you’ll have a few different methods for adding them to WordPress.

In the ‘Embed Options’ meta box, there are 4 different display options. You can even use multiple display options together. The simplest way is turning on the ‘Automatic Placement’ toggle.

Embed Options meta box

You can also display popular posts using Gutenberg Blocks in the new WordPress editor, with a shortcode, or by adding the widget to a sidebar.

To display your popular posts using Gutenberg Blocks open up a post or page you want to edit.

After that, click the ‘Add Block’ icon.

Add Gutenberg popular posts block

Search for ‘popular posts’ in the search bar and then choose the ‘Popular Posts’ or ‘Inline Popular Posts’ option.

Then, in the right hand sidebar, you can further customize the appearance of your popular posts.

Customize popular posts appearance

The settings are similar to the settings from the MonsterInsights plugin menu we highlighted above.

After you’ve finished adding and customizing the appearance of your popular posts, make sure you click ‘Publish’ or ‘Update’ to save your changes.

Now, your visitors will see your popular posts when they visit your website.

Method 2: Display Popular Posts by Views Without a Plugin in WordPress

If you don’t want to use a plugin, or you’re already using too many plugins, then you can use this code method.

There are some downsides to using this method. First, it involves adding code to WordPress, and it’s not beginner friendly.

Second, the code method isn’t as performance optimized as MonsterInsights plugin, so it will increase server load and can slow down your site if you have a lot of content.

With that said, let’s take a look at how to add popular posts in WordPress without a plugin.

In this method, you’ll need to add code to your WordPress files. If you haven’t done this before, then check out our beginner’s guide to pasting snippets from the web into WordPress.

Now that you know how to add code in WordPress, let’s go ahead and add the following code to your functions.php file, in a site-specific plugin, or by using a code snippets plugin.

function wpb_set_post_views($postID) {
    $count_key = 'wpb_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);
    }
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

The code above will detect post view counts and store it as a custom field for each post.

Once you add that function to WordPress, you need to call the function on your single post pages. Now, you need to tell the function which post gets credit for the views.

To do this, copy and paste the following code inside your single post loop.

wpb_set_post_views(get_the_ID());

If you are using a child theme, or you just want to make things easy for yourself, then you should simply add the tracker in your header by using wp_head hook.

To do this paste the following code in your theme’s functions.php file or the site-specific plugin (as shown above):

function wpb_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
    wpb_set_post_views($post_id);
}
add_action( 'wp_head', 'wpb_track_post_views');

Once you have placed this, every time a user visits the post, the custom field will be updated.

Note: If you are using a caching plugin, then this technique will not work by default. You could use Fragmented Caching feature that’s offered by some advanced caching plugins to bypass the caching plugins.

Now, you can do all sort of cool stuff such as display post view count, or sort posts by view count. Let’s take a look at how to do some of these cool things.

You can display the post view count on your single post pages, often next to the comment count, or your social share buttons.

To do this, add the following in your theme’s functions.php file or the site-specific plugin (highlighted above).

function wpb_get_post_views($postID){
    $count_key = 'wpb_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';
}

Then inside your post loop add the following code:

wpb_get_post_views(get_the_ID());

If you want to sort the posts by view count, then you can do so easily by using the the wp_query post_meta parameter.

The most basic example loop query would look like this:

<?php 
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();

the_title();

endwhile;
?>

To add other WP_Query parameters such as time range, refer to the WP_Query page in the Developers Handbook.

We hoped this article helped you learn how to display popular posts by views in WordPress. You may also want to see our guide on how to improve your WordPress SEO rankings, and our expert picks of the must have WordPress plugins for business websites.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

155 CommentsLeave a Reply

  1. Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

    • We do not have a recommended method for user specific popular posts at the moment.

      Admin

  2. If we have caching enabled, can we avoid the caching problem by resorting to JavaScript (AJAX) to send the command to record the view? Would that work?

    • While there is a complex way to have that workaround, we do not have a method we would recommend at this time.

      Admin

  3. Hello, thank you very much.
    It is very simple and practical.

    But with each reload, one visit is added.
    How can I fix this problem?

    Thankful

    • Any time a user would reload a page or visit the page again would be another visit. For specifically excluding refreshes you would need to use a plugin with more advanced features.

      Admin

    • You may want to try clearing all caching checking with your theme’s support to ensure they don’t have anything that would conflict with this

      Admin

  4. Thank you for the tutorial. I applied it and it works. No need another plugin to show popular posts and the customized counter in single.

    Thanks!

  5. Is it beyond the scope of this article to explain had you assign the functions to those buttons as in your screenshot:

    Recent Articles – Popular Posts – editor’s picks

    That is basically what I want to do…have buttons at the top of my posts page for recent, popular/trending, editors picks. I haven’t found any plugins that can do that. The all focus on side bar widgets.

    It looks like your article is starting to talk about this but where to go from there is beyond my current knowledge level.

    Thanks,
    Chris

  6. Getting double view count on refresh (single.php). Don’t know if the remove action is working or not for “adjacent_posts_rel_link_wp_head”. Useless so far. I tried everything that is possible to remove double count. Using this code in a custom made plugin.

  7. Thsi thing works greats.

    Now I want the columnn in admin to be sortable. any idea how to do this?

    many thanks!

  8. Hey, thanks for the code. Only issue I’m having is the view count is incrementing by 2 instead of 1 on refresh. Any thoughts?

    • This was happening for me because I had:

      `set_post_views(get_the_ID());` in single.php
      AND
      `add_action( ‘wp_head’, ‘track_post_views’);` in my functions.php which was also adding `set_post_views(get_the_ID());` within it.

      By removing the line on single.php I fixed the double count.

  9. Hello..

    Using w3total cache but count not working correctly.

    don’t use child theme. how can I fix it?

    thanks..

  10. Fixed this issue:

    Cannot use WP_Query, used get_posts and it is now working. Then use a foreach look to loop through the posts and display them. See below:

    $blog_cat_array = get_the_category();
    $blog_cat = $blog_cat_array[0]->term_id;

    $popularpost = array(
    ‘posts_per_page’ => 2,
    ‘meta_key’ => ‘wpb_post_views_count’,
    ‘orderby’ => ‘meta_value_num’,
    ‘order’ => ‘DESC’,
    ‘category’ => $blog_cat,
    ‘post_type’ => ‘post’,
    );
    $pop_posts = get_posts($popularpost);

    foreach($pop_posts as $pop_post){
    the_title();
    }

  11. I really like this option and have built it into my site.
    I have one question regarding the count. I found that the counts were rather high so I changed the code around a bit. With every count increase I wrote the IP address to a log file. I found hat two-third of the counts were legit and the other ones came from googlebot, apple, etc. and just now apews Is there any way to get the counts right and do you know if the ‘regular’ plugins have found a way around this?
    Thx!
    BTW: Keep up the good work, I thoroughly enjoy this site!

    • you can take maxmind ISP IP database and only count humans. This is the best option. Second just dont count common bots user-agent-names

      • Thanks so much. I will definitely look into that.
        In the mean time I implemneted the solution which was implemented in the WordPress Popular Posts plugin. That works for now, but the solution you recommended seems more future-proof. Thanks again!

  12. Hi! Awesome! This code helped me a lot!

    Do you know how to display the posts with 0 views? I have to enter to the post page by using the url the first time, otherwise it doesn’t show.

  13. Awesome thanks this is really useful, but a question. Doesn’t it slow down the loading of the page significantly?

  14. Hi,

    This is very useful post, i really appreciate. Can i filter the post in category, I wanted to show the post of specific category.

    Thanks.

  15. Ok this is great. For some reason, post count doesnt show numbers, not sure is it because i work on a local., but what i wanted to ask even more, is how to add so it count only in the last 7 days?

  16. I need advice on how r u to Load Word files to a WordPress website please. Is there an easy way?

  17. Sadly this does not work with W3 Total Cache with Page Caching enabled. Coul not get any “fragmented caching” to work either.

  18. Hey,
    This works great. But I need to show popular post of a day, this code shows popular posts of all time. Is there anyway to show popular posts of a day only.

    Any help will be greatly appreciated.

    Thanks :)

    • Try to add something like this in the WP Query

      ‘date_query’ => array(
      array(
      ‘year’ => $today[‘year’],
      ‘month’ => $today[‘mon’],
      ‘day’ => $today[‘mday’],
      ),

      • This doesn’t seems to work. Is there anyone who figures out how to display the most popular posts of the lasts 7 days?

        Thanks!

  19. Hi, I use Goodnews 5.7.2 theme, but where i put “wpb_get_post_views(get_the_ID());” in my theme, thank for u’r guidance

  20. Hey, thanks for the information.
    There’s a little problem. I put:

    function wpb_set_post_views($postID) {
    $count_key = ‘wpb_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);
    }
    }
    //To keep the count accurate, lets get rid of prefetching
    remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);

    function wpb_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
    global $post;
    $post_id = $post->ID;
    }
    wpb_set_post_views($post_id);
    }
    add_action( ‘wp_head’, ‘wpb_track_post_views’);

    function wpb_get_post_views($postID){
    $count_key = ‘wpb_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’;
    }

    and my visits counts always as two. What’s happening? Thanks.

    • I modified this a little to use it as a shortcode. To use this with a shortcode, add this to your functions.php:

      function wpb_set_post_views($postID) {
      $count_key = ‘wpb_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);
      }
      }
      //To keep the count accurate, lets get rid of prefetching
      remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);

      function wpb_track_post_views ($post_id) {
      if ( !is_single() ) return;
      if ( empty ( $post_id) ) {
      global $post;
      $post_id = $post->ID;
      }
      wpb_set_post_views($post_id);
      }
      add_action( ‘wp_head’, ‘wpb_track_post_views’);

      function wpb_get_post_views($postID){
      $count_key = ‘wpb_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 wpb_most_viewed_posts() {
      // start output buffering
      ob_start();
      ?>
      4, ‘meta_key’ => ‘wpb_post_views_count’, ‘orderby’ => ‘meta_value_num’, ‘order’ => ‘DESC’);

      //begin loop
      while ($query->have_posts()) : $query->the_post(); ?>

      <?php

      // Turn off output buffering
      $theResult = ob_get_clean();

      //Return output
      return $theResult;
      }
      // Create shortcode
      add_shortcode('wpb_most_viewed', 'wpb_most_viewed_posts');

      //Enable shortcode execution in text widgets
      add_filter('widget_text', 'do_shortcode');

      Then simply add [wpb_most_viewed] to your desired page/post and it should display your most popular posts.

  21. Hello, great tutorial but I have one question.
    After following all of the steps the template isn’t paginating. It’s only showing the default 10 posts. Should this happen or is there a way to get it to paginate?

  22. Folks, please help. Just cannot figure it out.

    How do I change the args to the wp-query to show the most popular posts for the last week? Or month?

  23. Hello,
    can I do this with comments? I dont use any comments on my site so I could use this comment count to check my most popular page without adding a comment?
    Cheers,
    Denis

  24. How do i make this work with w3 total cache? I’ve tried the fragment cache suggestion but changes nothing

  25. I’ve found a number of tuts covering this topic but none seem to spell out where the line goes.

    I’ve tried it inside PHP tags and it breaks the page. If i place it in the HTML it just renders as a comment when you view source and no php is generated.

    Any ideas? I’m w3 total cache and my page views aren’t getting updated

  26. Hello! How can I show the most popular posts for the current week?? Is there any possible? Thanks in advance.

  27. Hello,
    I’m using this code for months and it’s works great! That’s before I start using W3 Total cache and the code stop counting view for me.
    I struck at where and how do I need to put the mfunc code. Can you point that out for me?
    FYI, I put all of the codes in site-specific plugin.

  28. Hello,
    I’ve using this code for months and it’s work greats! That’s until I start using W3 Total Cache and this code stop count views for me.
    I’m struck at where do I need to put the mfunc to let the code work with cache. Can you point that out?
    FYI, I put all the code in a site-specific plugin.

  29. hello, I have some problem on how setting up like when the login user won’t include on the count while viewing any pages?? how to do that.. please need some help on these. thanks

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.