Displays the most viewed posts at the sidebar are very helpful for visitors to find out the most popular post of your site. This tutorial will show you the simple way to display the most popular posts by views without using any plugin. You can get the most popular posts using simple WordPress most viewed posts query.
We’ll use the post Meta for storing the post views count. Using the stored Meta value, we’ll fetch the posts according to the views count. You need to modify only two files functions.php
and single.php
. After that, you can display the most popular posts using simple posts query.
Open the functions.php
file of the activated theme and add the following code.
setPostViews()
function add or update the post meta with post_views_count
meta key.
/*
* Set post views count using post meta
*/
function setPostViews($postID) {
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '0');
}else{
$count++;
update_post_meta($postID, $countKey, $count);
}
}
Open the single.php
file from activated theme directory and place the setPostViews()
function inside the loop.
setPostViews(get_the_ID());
The following query will fetch the posts based on the post_views_count
meta key value. Place the following code in the sidebar or where you want to display the most popular posts list.
<?php
query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC');
if (have_posts()) : while (have_posts()) : the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile; endif;
wp_reset_query();
?>
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thanks a lot!
thanks for providing this code
Thank you. this is very effective for my theme.
it works fantastic bro. thanks a lot. by the way, how do I make this code to also display the post thumbnail in a grid/2 -3 column format?
It works. Thanks a lot, bro!