Hi,
I have custom fields with image from posts, and I want to display the top 5 posts sorting by views. I am using WordPress, can you help me please?
Sorry for my bad English.
Thanks.
Hi,
I have custom fields with image from posts, and I want to display the top 5 posts sorting by views. I am using WordPress, can you help me please?
Sorry for my bad English.
Thanks.
You must be logged in to post a comment.
There’s one error with Xhynk’s reference:
The query it runs returns posts in alphabetical order (1, 2, 20, 23, 3, 4, etc)
You just need to change
to
For the top 5, use:
It is very easy. Just use this code into your functions.php
put single.php
This is your popular post query:
For details go
http://www.wpbeginner.com/wp-tutorials/how-to-track-popular-posts-by-views-in-wordpress-without-a-plugin/
Basically it’s adding a meta field to each post – and deletes the old record when it’s viewed, then replaces it with ‘old record + 1’
Kabir Hossain’s solution can be shortened:
Since
get_post_meta()
returnsfalse
if no meta has been found, we can simply use this code to record views:((int)$count)
means that if$count
isfalse
it will become 0;Then, there’s no real need to delete post meta as there’s no way to decrease the number of views with our code. The function will run on the first post load and create the meta. If the meta has been created before this function has been run, then, well, we’ve had stats on this post that we can update.
Also, there’s no need for
add_post_meta
(especially adding 0 on the first view), as theupdate_post_meta()
will create meta if it does not exist.I also added a check to exclude admins from view stats and to allow this to run exlusively on posts, and hooked the function to template redirect: