fbpx
How to Show Most Popular WordPress Posts Without a Plugin

How to Show Most Popular WordPress Posts Without a Plugin

Heres a little trick on how to show a list of the most popular WordPress post by post read count – without using a plugin.

Instructions
Add this code to your functions.php file.

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' );

Then add this anywhere in your template where you wish to display the posts.

<?php
$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();
?>

WordPress Hosting

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress Snippet Info

Tested with Wordpress v. 4.7.3
Last Modified: 24.09.2017
Last Reviewed: 24.09.2017

How to Show Most Popular WordPress Posts Without a Plugin
3.4 (67.69%) 26 vote[s]
Please report broken snippets.
Report Broken Snippet
WordPress Hosting

Recent Comments