Without Plugin Display Popular Posts By Views In WordPress

Looking for displaying popular posts on your WordPress website without a plugin? then you are in the right place. Instead of displaying popular posts using plugin here, we going to display without a plugin by using simple functions. Based on the post count let us get the popular posts list and display on the home page or side widget.
The following code will count the post views based on post ID. Use the below code in your functions.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* Set post views count*/ function viewCount($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); } } |
Using the below code you can display the popular three (3) posts anywhere which you like (example: add the below code in your index/home or sidebar.php).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php $popular_posts_args = array( 'posts_per_page' => 3, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ); $popular_posts_loop = new WP_Query($popular_posts_args); while ($popular_posts_loop->have_posts()): $popular_posts_loop->the_post(); ?> <li> <!-- Post Title --> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> <!-- Post Image --> <?php the_post_thumbnail('delicious-recent-thumbnails'); ?> </li> <?php endwhile; wp_reset_query(); ?> |
Display Views Count in Your Post Page
If you like to display views count on your post page then use the below code in your single.php template.
1 2 3 4 5 6 7 8 9 |
<?php viewCount(get_the_ID()); $post_views = get_post_meta( get_the_ID(), 'post_views_count', true ); if ( ! empty( $post_views ) ) { ?> <p>Views: <?php echo $post_views; ?></p> <?php } ?> |
Conclusion:
I hope this article will help you to display popular posts by views without a plugin. Your support and comments are welcome here and if you liked this article share it with your friends.
Popular PostsPost ViewsWithout Pluginwordpress
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]