Categories
WordPress

How to display wordpress posts sorted by post view count [Solved: without a plugin]

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:

  1. 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)
  2. Open single.php file which is responsible to display each post in WordPress and paste this single line of code inside the loop
  3. You can display the post view count by using this line of code inside the WordPress loop on any page.
  4. We can display posts sorted by Post view counts by using the code below.

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 !! 🙂




By Subharanjan

Zend Certified Engineer (PHP), WordPress Developer, Software Engineer at Axelerant, India. I love PHP, MySql, Wordpress, BuddyPress, JavaScript, HTML5, CSS. Currently playing around with WordPress Development, Plugin Development, Theme Customization, Drupal. Subharanjan Mantri

85 replies on “How to display wordpress posts sorted by post view count [Solved: without a plugin]”

Man, nice tuto, but dont work for me. i dont use foreach, have to be used with foreach or while?
 
 

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 )

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?

In your example

‘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.

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.

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.

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.

May be you can set a weekly CRON to run and reset all the post count.

Example code:

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.

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 🙂

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:

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.

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.

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:

In WordPress 3.8 you need to change this:

to:

Thanks.

Thanks Fernando !! I will update the snippet above to this so this will be compatible for any version of WP.

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?

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.

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.

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="”>

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?

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.

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

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!

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

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:

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

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 */
}
?>

Leave a Reply