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)

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, increasing your pageviews and reducing your bounce rate.

The more your user engagement increases, the more Google thinks your content is good and important. In turn, your WordPress SEO improves and your site can rank higher.

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 posts 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 site theme’s CSS.

Then, you can choose how the widget should choose your most popular posts. For this tutorial, pick ‘Curated,’ but you can also display the most popular posts based on the number of comments.

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 created 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. This is what we did in our how to add featured posts in your WordPress sidebar article.

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

If you want to make the Popular Posts widget only appear on specific pages, then you can read our guide on how to show or hide widgets on certain WordPress pages.

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 WordPress tutorial helped you learn how to display popular posts by views. You may also want to check out our expert pick of the best related posts plugins for WordPress and our piece on what makes a high-converting landing page.

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

167 CommentsLeave a Reply

  1. mohadese esmaeeli

    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

      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

    • Mrteesurez

      Yes, competitors can use it to analytics ones website but you can just display it like WPbeginner, without adding the views count/counter.
      But mind you, visitors can use Semrush, Google, Similarweb and some other ways to analyze your site. You own is just to know how you are playing your games.
      Thanks for the insight.

  2. Moinuddin Waheed

    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

      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

  3. Jiří Vaněk

    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

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

      Admin

      • Jiří Vaněk

        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

          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.

  4. Amy Ling

    Is there a way to make it so it’s based on user vs in general?

    • WPBeginner Support

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

      Admin

  5. Chris

    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

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

      Admin

  6. thomas

    How can I reset the meta keys or reset the counting??
    Is there any function?

  7. saikat

    yes, very helpful tutorial

    • WPBeginner Support

      Glad our guide was helpful!

      Admin

  8. Amir

    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

      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

  9. locas

    only 4 posts :(
    I’ve tried to change to 10 but still 4 posts show up
    ‘posts_per_page’ => 10

    • WPBeginner Support

      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

  10. za

    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!

    • WPBeginner Support

      Glad our article could help :)

      Admin

  11. Chris

    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

  12. Sakshi Grover

    This was very helpful.!!! Thanks a ton.!

  13. Amit Biswas

    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.

  14. Hans

    Thsi thing works greats.

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

    many thanks!

  15. Trevor

    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?

    • Shwet

      I have the same problem with this code.
      Have you found any solution of this?

    • Fuchel

      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.

  16. Maya

    How to show most popular posts on my home page?

  17. Shaq

    How do I do this for a weekly basis, most viewed posts each week?!

  18. iftkhar hussain

    ah , this works fine ;
    thanks dear !

  19. Bülent Sakarya

    Hello..

    Using w3total cache but count not working correctly.

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

    thanks..

  20. Ryley Ameden

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

  21. Philipp

    Is there a possibility to count only unique visitors? Thank you

  22. Zeeshan

    Simple Awesome …. (Y)

  23. Erwin Barendregt

    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

      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

        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!

  24. HiepTD

    Hello, I am using WP Super Cache.
    I do not know how this code works correctly.

  25. Krishna

    It is not working for Custom Post Type. Can you help me on this please..

  26. John

    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.

  27. Gianmarco

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

  28. ayaz

    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.

  29. Md Maruf Adnan Sami

    How can i set Features post on Mobilepress Hompage?
    Please give me that code.

  30. gift charles

    Thank you for this awesome post, you guys are the best

  31. Bojan

    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?

  32. Blown

    Hi, How can I show the most popular posts for the current week??

  33. Ashish

    Awesome Article !! Thanks. Would be better if code was explained in detail.

  34. Dhiraj Kataria

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

  35. DarkSafka

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

    • Fakrul

      Same here @DARKSAFKA . Not working.

  36. Riya

    nice code. work perfectly….

    • hmmm

      you are right

  37. REIBI

    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

      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

        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!

    • Yonatan

      Add this code to the query

      ‘date_query’ => array(
      array(
      ‘after’ => ‘1 week ago’
      )
      )

  38. Mawardiy

    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

  39. Alex

    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.

  40. 6b

    Really great instruction no need of plugin.works perfect.

  41. Paritosh Arya

    What table does this custom field get stored into? Is it the posts table or the postmeta?

    • ScoDal

      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.

  42. Marcos

    Hello. Huge thanks for that. Works very well in my theme.

  43. John

    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?

  44. Varange

    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?

  45. Denis

    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

  46. Kes

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

  47. Kes

    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

  48. jarc100

    Thanks, this works as charm, but i didn’t get how to use it with the W3 Total Cache. :P

  49. Jorge

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

  50. Bigdragon13th

    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

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.