Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

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

Editorial Note: We earn a commission from partner links on WPBeginner. Commissions do not affect our editors' opinions or evaluations. Learn more about Editorial Process.

Do you want to display popular posts based on their views in WordPress?

By showing your most popular WordPress blog posts, you can help readers find your best and most valuable content. Plus, it can encourage them to stay longer on your website.

In this article, we’ll show you how to display your popular posts by views in WordPress.

How to Display Popular Posts by Views in WordPress

Why Display Popular Posts by Views in WordPress?

When users see your most popular WordPress blog posts, they can discover what content their fellow readers like the most. This way, they can check those articles out and join in on the conversation.

What’s more, displaying your most popular content in WordPress can boost your social proof. It’s like telling new users that, “Hey, other people have found these posts really helpful, and you might too!”

WPBeginner's trending and popular posts

Finally, showing your trending blog posts can make people stay longer on your website and explore more of your content.

The more your user engagement increases, the more Google thinks your content is good and important. In turn, your site can rank higher. Plus, this gives readers more time to convert, like signing up for your newsletter.

Unfortunately, WordPress doesn’t have a built-in feature or block to display your most popular posts by page views. In this guide, we will show you how to do exactly that with a plugin and with code.

Just click on one of the quick links below to jump straight to your preferred method:

Video Tutorial

Subscribe to WPBeginner

If you prefer written instructions, then just keep reading.

Method 1: Display Popular WordPress Posts by Views With MonsterInsights

The easiest way to display popular posts by views in WordPress is with a plugin. There are actually many WordPress popular post plugins available, but in our opinion, the best choice is MonsterInsights.

The MonsterInsights Google Analytics plugin

Used by 3 million+ websites worldwide, MonsterInsights is the best Google Analytics plugin for WordPress. While its main functionality is analytics, it also has a user-friendly feature to show your most popular posts.

First things first, you will need to install the MonsterInsights plugin and connect it to your Google Analytics account. For more details, see our step-by-step guide on how to install Google Analytics in WordPress for beginners.

Note: While a free version of MonsterInsights is available, we will be using the Pro version since it includes the popular posts feature.

Choose a Popular Posts Widget Theme

Once you’ve activated and set up the plugin, go to Insights » Popular Posts from the WordPress dashboard. Then, click the ‘Popular Posts Widget’ menu item.

The Popular Posts Widget in MonsterInsights

Scrolling down, you will need to select a theme to display the popular posts widget. There are various options.

Some include a featured image for the post, while some are more minimal-looking.

Choosing a popular posts widget theme in MonsterInsights

If you want to see what the theme looks like before making your choice, just move down the page to the Theme Preview section.

You can also preview the theme in a Wide or Narrow format. With the Wide format, you’ll see your posts listed under the page or post content, whereas the Narrow format displays the posts on the right side of it, like a sidebar.

Previewing the popular posts widget theme in MonsterInsights

Next, let’s scroll down to the ‘Customize Design’ section. Here, you can modify the theme’s colors, font size, layout, and post count to display.

The customization options here may vary depending on the theme you use. So, be sure to explore the different themes to see which one suits you best.

Customizing the popular posts widget theme in MonsterInsights

Configure the Popular Posts Widget Behavior

Once you’ve configured the theme’s design, you must go to the Behavior section. This is where you will control how the popular posts widget will appear on your WordPress website.

In the Widget Styling settings, you can choose to use the design that you’ve made above or opt to not style the widget at all. With the second option, the widget will follow your WordPress website theme’s CSS.

Then, you can choose how the widget should choose your most popular posts. Here, pick ‘Curated.’

Some of the popular posts widget's behavior settings in MonsterInsights

What you have to do next is enable the ‘Add Top 5 Posts from Google Analytics’ option below. But before doing that, you will need the MonsterInsights Dimensions Add-On and to add Post type as a new custom dimension.

This will let MonsterInsights choose the most popular posts based on Google Analytics data.

To do this, you have to download the MonsterInsights Dimensions Add-on and install it as a plugin in WordPress. For step-by-step instructions, check out our guide on how to install a WordPress plugin.

Next, go to Insights » Settings and switch to the ‘Conversions’ tab. After that, click ‘Add New Custom Dimension.’

Adding a new custom dimension in MonsterInsights

Once you’ve done that, select ‘Post type’ in the dropdown menu.

This will enable MonsterInsights to track the performance of your blog posts and other custom post types.

Selecting post type as a custom dimension in MonsterInsights

Now, just return to Insights » Popular Posts and go to ‘Popular Posts Widget.’

Simply activate the ‘Add Top 5 Posts from Google Analytics’ toggle button. Then, click ‘Test Automated Posts’ to see if the setup was successful.

Adding top 5 posts based on GA data in MonsterInsights

If yes, then you will see a success message popup.

It should say: ‘Popular Posts data can be fetched correctly. Please note: depending on when you set up the Custom Dimensions settings, it may take up to 7 days to see relevant Popular Posts data loading from Google Analytics.’

Popular posts data can be fetched correctly popup message in MonsterInsights

Moving on to the next steps, you can now add a title that will appear above the widget. It can be something like ‘Check Out Our Most Popular Posts’ or anything similar.

Below that, you can choose whether the widget should be displayed in all post types, be excluded from specific posts, and/or appear in certain post categories only.

These settings are useful if you have custom post types other than blog posts and feel like the popular posts widget will look irrelevant there.

More behavior settings for the popular posts widget in MonsterInsights

One of the last steps is to embed the popular posts widget. There are several options: placing it automatically, using a Gutenberg block, adding it as a sidebar widget, or using a shortcode.

Let’s go through each option one by one.

The embed options of popular posts widget in WordPress

Embed the Popular Posts Widget Automatically

Automatic Placement is recommended if you want the widget to show up on all the posts that match the Behavior settings you’ve set previously.

For this, all you have to do is activate the Automatic Placement button.

Activating automatic placement for the popular posts widget in MonsterInsights

The downside with this option is that you cannot adjust the widget’s design based on what looks best on the post or page. If you need this type of functionality, then you can try the next method.

Embed the Popular Posts Block to a Page or Post

If you want to have more control over how the widget looks on a page or post, then this method is for you.

First, go to the block editor of the post or page where you want the widget to be. After that, click the ‘+’ add block button anywhere in the editor and look for the Popular Posts block.

Adding MonsterInsights' popular posts block in the WordPress block editor

In the Block settings panel, you will see that there are options to change the widget’s theme, font size, colors, title, layout, and post count.

These settings are similar to the ones we’ve seen in the MonsterInsights plugin.

MonsterInsights' popular posts block settings in the WordPress block editor

The only difference is you can’t change which posts get chosen in the widget.

That said, in the Behavior Settings, it is possible to only show posts from certain categories. This way, you can make the popular post choices more tailored to your needs.

Choosing to only display posts from certain categories in the MonsterInsights popular posts widget

Once you are happy with the block settings, just click the ‘Update’ button in the post and page editor.

Here’s what the Popular Posts block looks like on our test website:

Example of what the MonsterInsights popular posts block look like on the WordPress site

Embed the Popular Posts Widget into a Sidebar

If you are using a non-block WordPress theme that has a widget-ready sidebar area, then you can add the Popular Posts widget to it.

All you have to do is go to Appearance » Widgets. Then, click the ‘+’ add widget button in the Sidebar area and look for the Popular Posts – MonsterInsights widget.

Adding the MonsterInsights popular posts widget to the sidebar area

Like in the previous method, the widget includes similar settings to customize your theme’s appearance.

What’s different is that the interface is slightly trickier to use. As you change the settings, you can’t see what the widget actually looks like. You will have to click on a different widget or another area to preview it.

If you are happy with how the widget looks, just click ‘Update’ in the top right corner.

Updating the sidebar area after adding the MonsterInsights popuplar posts widget

Make sure to go to your website to check if the sidebar looks right.

Here’s what ours looks like:

Example of the MonsterInsights popular posts widget in a sidebar

Embed the Popular Posts Widget With a Shortcode

The last option is to use a shortcode. This method is recommended if the above options don’t work for your specific use case.

In the Popular Posts Widget tab, scroll all the way down to the ‘Embed Options’ section. Then, choose ‘Display using a Shortcode’ and click the ‘Copy Shortcode’ button.

Copying the popular posts widget shortcode in MonsterInsights

After that, simply place the shortcode wherever you like. For more information, check out our guide on how to add shortcodes in WordPress.

Method 2: Display Popular WordPress Posts by Views With Code

The MonsterInsights method is the easiest way to display your most popular and best content by views in WordPress. But if you are comfortable with coding, then you can also use code to show your most popular WordPress posts.

For this method, we recommend using a code snippets plugin like WPCode, which is what we will use in this guide.

WPCode - Best WordPress Code Snippets Plugin

WPCode makes it safe to insert custom code without directly interacting with your WordPress files. Plus, since this method requires using multiple code snippets, the plugin will make managing and tracking them all much easier.

First, you need to install WPCode in WordPress. A free version of WPCode is available, but we will use the Pro version, as it comes with the features we need to insert the code in the right locations.

For a step-by-step installation guide, read our article on how to install a WordPress plugin.

Add WordPress Post Views Counter Function

Upon the plugin’s activation, you need to go to Code Snippets » + Add Snippet from the dashboard. Then, hover over ‘Add Your Custom Code (New Snippet)’ and click ‘Use snippet.’

Use snippet

Now, you are inside the WPCode code snippet editor. Before inserting any code, go ahead and add a title for the snippet.

For this first code, you can name it something like ‘WordPress Post Views Counter Function.’ This is because this first code’s purpose is to create a function for counting post views in WordPress.

Next, change the Code Type to ‘PHP Snippet.’ Note that every code snippet you will have to add from this article is in PHP.

Creating the WordPress Post Views Counter Function in WPCode

After that, you can copy and paste the following code below:

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);
    }
}
//Get rid of prefetching to keep the count accurate
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Now, just scroll down to the ‘Insertion’ section and select ‘Auto Insert’ for the Insert Method and ‘Run Everywhere’ for the Location. This works the same as inserting the code into your theme’s functions.php file.

After that, navigate to the top right side of the page and make the code active.

Then, click ‘Save Snippet.’

Choosing the insertion method and location in WPCode

At this stage, you need to add another new custom code snippet. You can name this one ‘Track Post Views Function Call.’

This code will call the function above and activate it on your single post pages.

Once you’ve done that, copy and paste the following snippet:

wpb_set_post_views(get_the_ID());

What’s different about this code snippet is you will choose the location ‘Insert After Post’ because it’s supposed to run on your single post pages.

Choosing Insert After Post as the code insertion location in WPCode

When you are done, just make the code active and save it.

Insert WordPress Post Views Tracking Hook

Now, you need to add a new code snippet that checks if the current page is a single post. If so, it will call the WordPress Post Views Counter Function to track and update the post’s view count.

This way, every time a user visits the post, its view count will get updated.

Let’s name this snippet ‘WordPress Post Views Tracking Hook.’ Then, insert the following lines of code:

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');

You can choose the insert method as ‘Auto Insert’ and the location as ‘Frontend Only.’

Same with the previous steps, just go ahead and activate the code and save the snippet.

Choosing Frontend Only as the code insertion location in WPCode

Note: If you are using a caching plugin, then this technique may not work by default. You could use the fragment caching feature that’s offered by some caching plugins like W3 Total Cache to make it work.

Add Functions to Retrieve Post Views Count and Display Most Popular Posts With View Counts

We are now in the final steps of this guide. You need to add a code snippet that retrieves and formats the number of views for a given WordPress post. This will come in handy later when displaying the list of most viewed posts.

You can name this code as ‘Retrieve Post Views Count Function’ and set the location to ‘Run Everywhere.’

Here is the code snippet:

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';
}

Again, be sure to make the code active in WPCode and save it after.

Once you’ve done that, create a new code snippet again and name it ‘Display Most Popular Posts with View Counts.’ This is the code that will show your most popular posts at the bottom of your blog posts.

In the Code Preview box, insert the following snippet:

// Customize the query parameters as needed
$popularpost = new WP_Query( array(
    'posts_per_page' => 3,         // Feel free to adjust the number of posts to display
    'meta_key' => 'wpb_post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
));
?>

<div class="popular-posts">
    <h2>See Our Most Popular Posts</h2> <!-- Feel free to customize the title -->
    <ul>

    <?php while ( $popularpost->have_posts() ) : $popularpost->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            - <?php echo wpb_get_post_views(get_the_ID()); ?>
        </li>
    <?php endwhile; ?>

    </ul>
</div>

<?php wp_reset_postdata(); 

As noted in the code, feel free to adjust the number of posts to display and customize the title for this section.

In the WPCode Insertion section, make sure to select ‘Insert After Post’ for the Location. Then, just make the code active and save the snippet.

All that’s left to do now is visit one of your blog posts and see if the code works. Here is what the most popular posts by views section look like on our test WordPress blog:

What the most popular posts by views section looks like made with WPCode

Expert Tip: To see if your code works without permanently changing your site, you can try WPCode’s Testing Mode.

This feature lets you add your codes like normal and only you can see what they look like on the front end. On the other side, your users will interact with your website as normal.

We hope this article helped you learn how to display popular posts by views in WordPress. You may also want to check out our article on how to display popular products in WooCommerce and our beginner’s guide to WordPress custom fields.

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.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

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

163 CommentsLeave a Reply

  1. Syed Balkhi says

    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!

  2. mohadese esmaeeli says

    The display of popular posts is beneficial as it helps increase website traffic statistics. However, on the other hand, competitors can easily identify which posts and topics have been popular on your site. One of the sections I always explore for competitor analysis and finding trending topics is the “most popular articles” section on various websites.

    • WPBeginner Support says

      While that can be something to keep in mind, we normally find it best to add what is most important to your visitors instead of being concerned that your competitors will follow your content.

      Admin

  3. Moinuddin Waheed says

    Popular posts and related posts makes the user engagement intact and reduced bounce rate.
    it helps in more user interaction with the posts and articles.
    I have seen many bloggers showing views count and read time of the posts, like 5 minutes read or 3 minutes read.
    can we have popular posts and related posts where ever we want with this method? and
    Is this method can be used for achieving both these objectives like having read time based on word counts?

    • WPBeginner Support says

      You should be able to place it wherever widgets are allowed. For the time to read, it would depend on the plugin you use for that and if it has an integration or not.

      Admin

  4. Jiří Vaněk says

    I would like to ask if the snippet also works on the new WordPress 6.4.2. I followed the instructions, cleared the cache, but the most read articles do not appear under the article

    • WPBeginner Support says

      The code snippets should still work with the most up to date version of WordPress.

      Admin

      • Jiří Vaněk says

        Thank you for the reply. It’s already working. I had a mistake somewhere and unfortunately I don’t know where. In the end, I repeated the whole procedure twice more and it worked on the third try. Unfortunately, I don’t know what I did wrong, but the snippets really work. Thank you.

        • WPBeginner Support says

          Glad they started working for you, it’s always difficult to tell what went wrong when trying the same code again works when the previous time it didn’t.

    • WPBeginner Support says

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

      Admin

  5. Chris says

    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?

    • WPBeginner Support says

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

      Admin

  6. Amir says

    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

    • WPBeginner Support says

      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

    • WPBeginner Support says

      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

  7. za says

    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!

  8. Chris says

    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

  9. Amit Biswas says

    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.

  10. Hans says

    Thsi thing works greats.

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

    many thanks!

  11. Trevor says

    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?

    • Fuchel says

      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.

  12. Bülent Sakarya says

    Hello..

    Using w3total cache but count not working correctly.

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

    thanks..

  13. Ryley Ameden says

    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();
    }

  14. Erwin Barendregt says

    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!

    • bah says

      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

      • Erwin Barendregt says

        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!

  15. John says

    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.

  16. Gianmarco says

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

  17. ayaz says

    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.

  18. Bojan says

    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?

  19. Dhiraj Kataria says

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

  20. DarkSafka says

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

  21. REIBI says

    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 :)

    • Dimitrios Arkolakis says

      Try to add something like this in the WP Query

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

      • Nick Heurter says

        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!

  22. Mawardiy says

    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

  23. Alex says

    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.

    • ScoDal says

      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.

  24. John says

    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?

  25. Varange says

    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?

  26. Denis says

    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

  27. Kes says

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

  28. Kes says

    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

  29. Jorge says

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

  30. Bigdragon13th says

    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.

Leave a Reply to AJ Cancel 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.