Several plugins are there which displays the posts according to number views( number of times the post is viewed). We can achieve the same thing without using a plugin. We can use this code in a particular WordPress theme files. Also it’s very easy to sort the posts according to the post views. Even, we can use the view count to display it side to each post.
Steps:
- Paste the code below into your current theme’s function.php file. Try to use child theme if you are not already having one.(Child theme is optional though)
/** * To display number of posts. * * @param $postID current post/page id * * @return string */ function subh_get_post_view( $postID ) { $count_key = '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'; } /** * To count number of views and store in database. * * @param $postID currently viewed post/page */ function subh_set_post_view( $postID ) { $count_key = 'post_views_count'; $count = (int) get_post_meta( $postID, $count_key, true ); if ( $count < 1 ) { delete_post_meta( $postID, $count_key ); add_post_meta( $postID, $count_key, '0' ); } else { $count++; update_post_meta( $postID, $count_key, (string) $count ); } } /** * Add a new column in the wp-admin posts list * * @param $defaults * * @return mixed */ function subh_posts_column_views( $defaults ) { $defaults['post_views'] = __( 'Views' ); return $defaults; } /** * Display the number of views for each posts * * @param $column_name * @param $id * * @return void simply echo out the number of views */ function subh_posts_custom_column_views( $column_name, $id ) { if ( $column_name === 'post_views' ) { echo subh_get_post_view( get_the_ID() ); } } add_filter( 'manage_posts_columns', 'subh_posts_column_views' ); add_action( 'manage_posts_custom_column', 'subh_posts_custom_column_views', 5, 2 );
- Open single.php file which is responsible to display each post in WordPress and paste this single line of code inside the loop
<?php subh_set_post_view( get_the_ID() ); ?>
- You can display the post view count by using this line of code inside the WordPress loop on any page.
<?php echo subh_get_post_view(get_the_ID()); ?>
- We can display posts sorted by Post view counts by using the code below.
<?php $args = array( 'numberposts' => 4, /* get 4 posts, or set -1 to display all posts */ 'orderby' => 'meta_value', /* this will look at the meta_key you set below */ 'meta_key' => 'post_views_count', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish' ); $myposts = get_posts( $args ); foreach ( $myposts as $mypost ) { /* do things here */ } ?>
WordPress plugins for post view counts are good but those provide extra functionalities which are not really needed for most of the cases; so why to bloat the setup and add to the response load of the website. Fastness of website matters !! 🙂
Man, nice tuto, but dont work for me. i dont use foreach, have to be used with foreach or while?
<?php
$args = array(
'post_type' => 'djs',
'taxonomy' => 'top-djs',
'numberposts' => 1,
'orderby' => 'meta_value',
'meta_key' => 'post_views_count',
'order' => 'DESC',
'post_status' => 'publish'
);
$ranking = 0;
?>
<?php query_posts($args); ?>
<?php if ( have_posts() ) : ?>
<?php while ( have_posts()) : the_post();
$ranking++; ?>
Hi Anderson,
Your approach is correct and it will work on any type of loop construct. I guess your problem is due to the ‘taxonomy’ paramater which is not correct.
Try putting the taxonmy parameter like below ( or if it is a category, then use category id like this: ‘category’ => 1 )
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'top-djs',
'field' => 'slug',
'terms' => array('top-djs_1', 'top-djs_2', 'top-djs_3'),
)
)
);
For more info. on list of parameters and its usage refer this: http://subharanjan.com/list-of-parameters-that-can-be-pass-through-wp_query-constructor-to-create-a-new-query-object-in-wordpress/
Thanks for reply Subharanjan, but i still don’t understand some things, my loop would look like?
<?php
$args = array(
'post_type' => 'djs',
'orderby' => 'meta_value', /* this will look at the meta_key you set below */
'meta_key' => 'post_views_count',
'order' => 'DESC',
'post_status' => 'publish'
'numberposts' => 1,
'tax_query' => array(
array(
'taxonomy' => 'estilo',
'field' => 'estilo',
'terms' => array('top-djs'),
)
)
);
?>
In your example
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'top-djs',
'field' => 'slug',
'terms' => array('top-djs_1', 'top-djs_2', 'top-djs_3'),
)
)
);
‘taxonomy’ => ‘top-djs’, is the taxonomy that i created in functions or added as a post category? edit-tags.php?taxonomy=estilo&post_type-djs This taxonomy?
‘field’ => ‘slug’, is the word slug even if they will or should i replace with the slug of the taxonomy to the top?
top-djs_1′, ‘top-djs_2’, ‘top-djs_3 Why 3 types, or 3 slugs?
This is correct.
'tax_query' => array(
array(
'taxonomy' => 'estilo',
'field' => 'estilo',
'terms' => array('top-djs'),
)
)
I had written as to show you that you have to pass the “Taxonomy” along with its “Terms”, as I was not sure what is your taxonmy and terms.
Glad that you figured out and it worked.
http://andersonnarciso.com/views.jpg see
Mannnn thanks, now work! I found a “bug” on the functions which was doing the posts being random, fix and now is working, thank you very much for your tutorial, I’ll publish it on my blog.
It’s saved my life. Thank you guys.
Tried it and it works, but when I sort posts by views a post with 200 views would be shown before a post with 1000 views. It’s sorting by the first number so a post with 9 views would come before a post with 8000000.
Any way to change this so it would be 85,10,9,8,5 and not 10,9,85,8,5?
Hi Mills, just change the sorting param “orderby” to “meta_value_num” and it should work.
4, /* get 4 posts, or set -1 for all */
'orderby' => 'meta_value_num',
'meta_key' => 'post_views_count',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
$myposts = get_posts( $args );
foreach( $myposts as $mypost ) {
/* do things here */
}
?>
Yes! Thanks!
thanks
Is it possible to reset this counter? So for example I want to display my popular posts of the week.
May be you can set a weekly CRON to run and reset all the post count.
Example code:
604800, // 1 week in seconds
'display' => __( 'Once Weekly' ),
);
return $schedules;
}
// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'subharanjan_weekly_cron_action' ) ) {
wp_schedule_event( time(), 'weekly', 'subharanjan_weekly_cron_action' );
}
// Hook into that action that'll fire weekly
add_action( 'subharanjan_weekly_cron_action', 'subharanjan_reset_postview_counters' );
function subharanjan_reset_postview_counters() {
$count_key = 'post_views_count';
$args = array(
'numberposts' => -1,
'meta_key' => $count_key,
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters'=> true
);
$postslist = get_posts( $args );
foreach ($postslist as $singlepost) {
delete_post_meta($singlepost->ID, $count_key);
// or reset all the post's count to 0
//update_post_meta($singlepost->ID, $count_key, '0');
}
}
?>
Amazing, thank you much! I am going to familiarize myself CRON jobs.
Hi Mr. Mantri! Can you explain please how to reset all post count values? Clean custom fields throughout the site is far too long ))) Thank you!
Hi Alex, The answer lies in my previous reply @trewknowledge.
You can hook this function and it will delete all the custom fields values. If you want you can reset all the custom field values to 0.
function subharanjan_reset_postview_counters() {
$count_key = 'post_views_count';
$args = array(
'numberposts' => -1,
'meta_key' => $count_key,
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters'=> true
);
$postslist = get_posts( $args );
foreach ($postslist as $singlepost) {
delete_post_meta($singlepost->ID, $count_key);
// or reset all the post's count to 0
//update_post_meta($singlepost->ID, $count_key, '0');
}
}
Does this snippet for the last week most post views goes into function.php and if it does does we replace the first one with this?
Thank you for your kind!
I tried to use the code from your previous reply, but get T_VARIABLE error in line $schedules[‘weekly’] = array(
But your second solution works fine, thanks again!
Hello, thx for great tut, but I have a little one problem. My counter add 2 viewes instead of 1. Where should be a problem, please? Thank you!
btw sorry for ma English, I hope that you can understand ma question 🙂
It can be anything.. have you called the function ” setPostViews(get_the_ID()) ” two times in the single.php file ?
Or if you can provide me more details then I can help you. 🙂
Here is my single.php http://pastebin.com/9nqX2eyv If you can help me I will be grateful.
I don’t see any problem in the single.php file. Still you can do the following
— Check if the same key has been used multiple times in your current theme ‘post_views_count’
— Bring the line ‘setPostViews(get_the_ID());’ from the loop and paste just below the get_header like this:
setPostViews( $post->ID );
Hello,
I encountered with the same problem.
I didn’t fix it, but I found that the function was called two times when I’m logged to the admin.
If I comment the wp_footer , it’s ok.
Subharanjan Mantri, if you have an idea, it would be usefull !!
Thank you for your work, it help me.
Hey Subharanjan. How do I display the most popular posts for “today” only? Thanks!
Hi Felipe, this snippet doesn’t store date information into the DB along with the count. So, you have to store the counts along with date and write query to get the counts for each post date wise.
I mean, I want to display most popular for 24 hours, after 00:00 reset all information to recount. I dont want to get the number from a specific day.
/**
* On an early action hook, check if the hook is scheduled - if not, schedule it.
*/
function subharanjan_setup_schedule() {
if ( !wp_next_scheduled( 'subharanjan_daily_event' ) ) {
wp_schedule_event( time(), 'daily', 'subharanjan_daily_event' );
}
}
add_action( 'wp', 'subharanjan_setup_schedule' );
/**
* On the scheduled action hook, run a function.
*/
function subharanjan_do_this_daily() {
// do something every day
subharanjan_reset_postview_counts();
}
add_action( 'subharanjan_daily_event', 'subharanjan_do_this_daily' );
/**
* function to reset the post view counts.
*/
function subharanjan_reset_postview_counts() {
$count_key = 'post_views_count';
$args = array(
'posts_per_page' => -1,
'meta_key' => $count_key,
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true,
'no_found_rows' => true,
'fields' => 'ids',
);
$postslist = get_posts( $args );
foreach ( $postslist as $singlepostid ) {
// reset all the post's count to 0
update_post_meta( $singlepostid, $count_key, '0' );
}
}
No posts are displayed. I followed the instructions. there’s no meta key being added to database. (need your help urgently)
This is my plugin file code:
Hi Mr. Mantri,
I’ve your tuto but i can get the post which is ordered by views.
Here is my loop: http://pastebin.com/dyJ8SLQd
Please improve me !
Pingback: Bookmark 2013 | emilio
In WordPress 3.8 you need to change this:
'orderby' => 'meta_value'
to:
'orderby' => 'meta_value_num'
Thanks.
Thanks Fernando !! I will update the snippet above to this so this will be compatible for any version of WP.
'orderby' => 'meta_value meta_value_num'
Hi,
I have used the code to sort by # views, however the page will only show new posts created after adding counter code to single.php. I’m guessing this is because the query args are looking for the key post_views_count which does not exist for new posts. How can we fix this?
$args = array(
'numberposts' => -1
'orderby' => 'meta_value_num',
'meta_key' => 'post_views_count',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'cat' => $catid
);
query_posts( $args );
Thanks
Gary.
Correction – It’s not just new pages, the query only shows pages viewed since adding in the code to single.php which create the meta value. We have a site with over 1000 pages so we don’t want to go and view each one ourselves to set the mata tag..
Thanks.
Thats correct Gary. This is how it stores and gets the post view counts. For the old posts which doesn’t have any view counts, you should try considering the number of comments for each post or some other aspect to get these sorted as per some rules. As far as default WordPress is considered, there is no such field which keeps the view count for posts.
this code is not working, please check this code, I’m using my site http://www.agriculturetune.com, but not show view count, please help.
Hi Subharanjan, great tutorial and post. Very helpful to me.
I’m having a small issue… here’s my query:
3, /* get 4 posts, or set -1 for all */
‘orderby’ => ‘meta_value_num’,
‘meta_key’ => ‘post_views_count’,
‘order’ => ‘DESC’,
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’
);
$my_query = new WP_Query($args);
?>
have_posts() ) : ?>
have_posts()) : $my_query->the_post(); ?>
in_the_loop = true;
?>
For some reason, my “numberposts” is not working! It’s always pulling all posts in with greater than 100 views. Could you advise on this?
Thanks so much.
Dear Subharanjan, awesome snippet and I am using it for 6 months. Works perfect. Is it possible to get and display top posts by vies count? Thank you in advance for your help.
Extremely helpful tutorial. Thanks!
Great , I was looking for that solution, Thanks
Nice one, Subharanjan. Should work really well to show popular posts on a different category style page.
On my site running WP 3.9.1, the posts all show “0 View” no matter how many times they are viewed.
The above code is not WP version biased. Please check at your end. There might be some issues.
Why is this function not counting mobile views?
Thanks a lot. You just saved my day 🙂
Hello Subharanhan lovely function! i’ve been using it for 2 years now and its perfect! Just one problem, the results are not sorted correctly by metas_value_num or meta_value. It gets the top 6 posts but they are not sorted in the displayed list.
For example: Post 1 (100 views), Post 5 (92 views), Post 76 (200 views)
This is the code that i’m using.
6,’meta_key’=>’post_views_count’,’orderby’=>’meta_value_num’, ‘order’=>’DESC’);
$custom_query = new WP_Query($args);
while($custom_query->have_posts()) : $custom_query->the_post(); ?>
<a href="”>
thanks very much 🙂
Welcome !!
I don’t want to add the code to single.php . Instead of add on single.php can i add it to the page where it needed to be displayed?
Read the article !! 🙂
Do I have to paste it into a certain section in my functions.php file? I’ve tried pasting it into several different areas (one at each time of course) and it errors out displaying a white page.
Yes, these code can be pasted into the currently active theme’s functions.php file.
Does it need to be before or after a certain part of code in my functions file? I pasted the code in the functions file and I reloaded the page and it error’d to a blank page.
Hello, thanks for the code is really cool.
I want one more thing but i dont know how to do. I want to show most popular in 2 days not in all my site how can i do that? I try it to add days=2 but no lucky.
Thank in advance
First off just let me say thank you so much for what you have here already, Im so close to my goal I can almost taste it but Im not quite there yet. Im trying to set up my index page so that it displays the most popular post for each of the 6 categories (and their children) that I have. I followed everything you have here to the letter but for some reason I am not returning anything at all. I could really use a little help. Heres a snippet from one of the loops I have: http://pastebin.com/ir3qHJQT
If you could point out what Im doing wrong, I would appreciate it infinitely
Thanks for your time
–> Please check if you are storing the ‘post_views_count’ properly and these actually getting stored into DB(wp_postmeta) or not.
–> Also, try to use meta query to deal with situation when the posts are not visited even once. http://wordpress.stackexchange.com/a/81831/13615
I used the optional code in the get/set postviews and its confirming that it has more views than anything else…Im really not sure what is going on here but I keep turning up with nada
Nevermind, I figured it out. It was a problem in the query…kinda a rookie mistake but cest la vie. Still I thank you for helping me diagnose the problem and paving the way in the first place. Cheers, and happy coding!
SO GOOD! THANK U!
see my question here:
http://stackoverflow.com/questions/31614161/i-want-to-display-the-most-popular-posts-for-today-in-wordpress-and-this-list?noredirect=1#comment51179113_31614161
Sorry, for my english, but i have problem. How can i set the sortable post views? I can see the post views in my Admin dashboard, but is it not sortable 🙁
You can follow this snippet and add sortable feature to the column. http://wordpress.stackexchange.com/a/49321/13615
Hello!
I’m triying to insert this code in my website but I have some problems:
I would like to display the post sorted by post view in all categorys, but I dont know where I have to paste the code’s.
The first one is in the functions.php, right.
The second one () is in the single.php
But I don’t know in which one I have to paste the 3º and the 4º.
I tried in the functions.php on my theme but didnt work. could you help me? I’m a noob in wp! thanks a lot.
Hi Javier, Thanks for reaching out. You have to customize the code a little to get the category specific posts and order those according to the post views count. To display the posts sorted according to views, you have to customize inside `category.php` and `archive.php`files. Please read the WP template hierarchy: https://developer.wordpress.org/themes/basics/template-hierarchy/ Thanks !!
Hi again mate, thank you for your reply.
I think that I didnt explain my problem with clarity.
Im looking for a pluging or code that allows my web users to filter the posts with a dropdown like “sort by popularity”, “short by newness” like in woocommerce.
Like this http://themes.fruitfulcode.com/fruitful/shop/ but with post in the categoryes not with products.
is there something like this? I dont know if with you code I could do something like that, if not, could you let me know if is possible?
Thank’s a lot!!!
Hi Javier,
You should try one of these plugins below:
https://wordpress.org/plugins/archive-posts-sort-customize/
https://wordpress.org/plugins/wp-sort-posts/
Let me know if this helps !! Thanks 🙂
when i am adding new post the views are not updating for new posts
How would I go about and echo the total view count of all posts?
how can displaying specific post count views to other page/post?
Hi,
i am facing an issue with this
the problem is that i am only seeing 0 Views for all my posts
it is not updating the views count…
http://awesomescreenshot.com/0f25ixilea
Please make sure to set and increase the view count in single.php file. `subh_set_post_view( get_the_ID() );`
Hi Subharanjan,
I am read your article. It’s nice. Your article is useful for woocommerce product sorting. I want to short product by It’s popularity (With Number of views per product). ? If yes then can you please here give me the solutions.
Thanks,
Ketan.
I am use following code but it’s not working i think:
<?php
function subh_get_post_view( $postID ) {
$count_key = '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 subh_set_post_view( $postID ) {
$count_key = 'post_views_count';
$count = (int) get_post_meta( $postID, $count_key, true );
if ( $count
Hi Ketan,
Thanks for reaching out. You have to do some changes into the code to save and fetch view count for `product` post type. Maybe you could look into the plugin code here: https://wordpress.org/plugins/woo-most-viewed-products/ which does exactly the same you want.
Thanks !!
What about caching. Will supercache/w3 ruin this. Will it work with cache plugins?
Thanks for reaching out. I haven’t tried this with a cache plugin yet 😛 Will try and let you guys know.
Hello, thank you for useful post. I have a problem, my post counter isn’t updating. I’m getting stuck at 0 views.
I did place the
Inside news-single.php loop.
I’m sure this is the right file, because simple.php only contains this:
ID, THEME_NAME."_sidebar_position", true );
if($post_type == OT_POST_GALLERY) {
get_template_part(THEME_INCLUDES.'gallery-single','style-1');
} else if($post_type == OT_POST_PORTFOLIO) {
get_template_part(THEME_INCLUDES.'portfolio-single');
get_footer();
} else {
get_template_part(THEME_INCLUDES.'news','single');
get_footer();
}
?>
Also, I placed the code that shows the counter itself to “news-single.php” and the counter appeared well. But it still isn’t updating at all, I don’t know why 🙁
PS I tried to place
`subh_set_post_view( get_the_ID() );`
Below
`get_template_part(THEME_INCLUDES.’portfolio-single’);`
and other lines in single.php but it didn’t work neither
Hi Danil,
Does it throw any error ? `news-single.php` is the correct file to be edited. This need to be debugged to find what causing the issue. Can you please provide me the content of `news-single.php` and `functions.php` file to help you better ? [ make a pasteit here: https://justpaste.it/ ]
hi Subharanjan
can we show most viewed post for each category ?
for example 5 most viewed of android category
Hi Hadi,
Please check the comment here: http://subharanjan.com/how-to-display-wordpress-posts-sorted-by-post-view-count-solved-without-a-plugin/#comment-47
Thanks,
Subh
when i go to link page, the visitor counter increase by 2. whats the problem>
Wonder if can use this method for woocommerce product slider.
Thaks for all help, Well yes Plugins are big help these day and I love to have them, but yes their is lot of security issues. This code is solving my major issues.
Hi Subh,
I am a total newbie to wordpress and still trying to figure out where step 4 of your code goes. I am working with a child theme. Which php file do I add the following code to?
4, /* get 4 posts, or set -1 to display all posts */
‘orderby’ => ‘meta_value’, /* this will look at the meta_key you set below */
‘meta_key’ => ‘post_views_count’,
‘order’ => ‘DESC’,
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’
);
$myposts = get_posts( $args );
foreach ( $myposts as $mypost ) {
/* do things here */
}
?>