In to post i will explain How to display most popular posts without a plugin in your wordpress website. This code will display most popular post by post read count – without using any plugin.
When i was junior wordpress developer i got request from one of my current client to display only most popular posts in sidebar without using any wordpress plugin. So i have done and think to share with my blog visitors.
Copy below snippets and paste at the end of in your functions.php page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function count_post_visits() { if( is_single() ) { global $post; $views = get_post_meta( $post->ID, 'my_post_viewed', true ); if( $views == '' ) { update_post_meta( $post->ID, 'my_post_viewed', '1' ); } else { $views_no = intval( $views ); update_post_meta( $post->ID, 'my_post_viewed', ++$views_no ); } } } add_action( 'wp_head', 'count_post_visits' ); |
Now add below in your template where you want to display.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $popular_posts_args = array( 'posts_per_page' => 3, 'meta_key' => 'my_post_viewed', '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(); // Loop continues endwhile; wp_reset_query(); |
Thank you for giving time on freewebmentor community. Please don’t forget to subscribe our newsletter or join us on Facebook and Twitter to be the first to learn the next great thing from freewebmentor.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: popular post plugin, popular posts widgets, wordpress, wordpress functions, wordpress hooks, wordpress popular posts, wordpress posts, wordpress tips and tricks