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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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!
Amy Ling says
Is there a way to make it so it’s based on user vs in general?
WPBeginner Support says
We do not have a recommended method for user specific popular posts at the moment.
Admin
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
thomas says
How can I reset the meta keys or reset the counting??
Is there any function?
WPBeginner Support says
If you’re using the custom code method, it is saved as a custom field in which case you can edit the count in the edit post area itself. You can see more on custom fields in our guide below:
https://www.wpbeginner.com/wp-tutorials/wordpress-custom-fields-101-tips-tricks-and-hacks/
Admin
saikat says
yes, very helpful tutorial
WPBeginner Support says
Glad our guide was helpful!
Admin
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
locas says
only 4 posts![:(](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
I’ve tried to change to 10 but still 4 posts show up
‘posts_per_page’ => 10
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
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!
WPBeginner Support says
Glad our article could help
Admin
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
Sakshi Grover says
This was very helpful.!!! Thanks a ton.!
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.
Hans says
Thsi thing works greats.
Now I want the columnn in admin to be sortable. any idea how to do this?
many thanks!
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?
Shwet says
I have the same problem with this code.
Have you found any solution of this?
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.
Maya says
How to show most popular posts on my home page?
Shaq says
How do I do this for a weekly basis, most viewed posts each week?!
iftkhar hussain says
ah , this works fine ;
thanks dear !
Bülent Sakarya says
Hello..
Using w3total cache but count not working correctly.
don’t use child theme. how can I fix it?
thanks..
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();
}
Philipp says
Is there a possibility to count only unique visitors? Thank you
Zeeshan says
Simple Awesome …. (Y)
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!
HiepTD says
Hello, I am using WP Super Cache.
I do not know how this code works correctly.
Krishna says
It is not working for Custom Post Type. Can you help me on this please..
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.
Gianmarco says
Awesome thanks this is really useful, but a question. Doesn’t it slow down the loading of the page significantly?
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.
Md Maruf Adnan Sami says
How can i set Features post on Mobilepress Hompage?
Please give me that code.
gift charles says
Thank you for this awesome post, you guys are the best
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?
Blown says
Hi, How can I show the most popular posts for the current week??
Ashish says
Awesome Article !! Thanks. Would be better if code was explained in detail.
Dhiraj Kataria says
I need advice on how r u to Load Word files to a WordPress website please. Is there an easy way?
DarkSafka says
Sadly this does not work with W3 Total Cache with Page Caching enabled. Coul not get any “fragmented caching” to work either.
Fakrul says
Same here @DARKSAFKA . Not working.
Riya says
nice code. work perfectly….
hmmm says
you are right
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!
Yonatan says
Add this code to the query
‘date_query’ => array(
array(
‘after’ => ‘1 week ago’
)
)
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
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.
6b says
Really great instruction no need of plugin.works perfect.
Paritosh Arya says
What table does this custom field get stored into? Is it the posts table or the postmeta?
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.
Marcos says
Hello. Huge thanks for that. Works very well in my theme.
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?
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?
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
Kes says
How do i make this work with w3 total cache? I’ve tried the fragment cache suggestion but changes nothing
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
jarc100 says
Thanks, this works as charm, but i didn’t get how to use it with the W3 Total Cache.
Jorge says
Hello! How can I show the most popular posts for the current week?? Is there any possible? Thanks in advance.
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.
Bigdragon13th says
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.
AJ says
Hell this is great! How would I display the view count outside of the post loop like in the sidebar?
leslie says
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