How to display WordPress Popular Posts based on Views

You may want to display popular posts widget in your WordPress site. It serves as a great way to introduce your readers to the most popular contents. The contents you want to show may be posts or pages. Here I am going to show you how you can track and display most popular posts. Having most popular posts displayed on your sidebar widget, it increases the page views and reduces the bounce rate.

There are number of plugins available for WordPress CMS (content management system) but there are number of unnecessary functions are written in the plugins and this may cause slowness of your site. When you need more control over your code then you need to write your own code to create such plugin.

Prerequisites

PHP 7.3.5 – 7.4.3, WordPress 5.5 – 5.7, MySQL 8.0.17 – 8.0.22

Track Post Views Count

As a first step you need to store view counts for each post in a custom field. The following function will do the thing you need. Either you can create in the theme’s or child theme’s functions.php file or in the plugin file.

function roytuts_set_post_views($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
	
    if($count=='') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

In the above function I have specified a meta key (post_views_count) that is used to keep track of the view counts for each post. Next I have retrieved the count for the current post which is being viewed by the user. If count is not found then I am first deleting the meta key if exists and adding the meta key with count 0.

Now the above function can be called inside a single post loop:

roytuts_set_post_views(get_the_ID());

Or you can make the things easy and put the below code snippets in the theme’s or child theme’s function.php file:

function roytuts_track_post_views ($post_id) {
    if ( !is_single() ) return;
	
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
	
    roytuts_set_post_views($post_id);
}

add_action( 'wp_head', 'roytuts_track_post_views');

You need to get rid of pre-fetching and you can do so by the following line of code otherwise you will not see the correct count for post views:

remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Now to show your popular posts, you can use the following code snippets. You ideally may want to put the below code into your plugin to show it on the widget area.

//Set the parameters / arguments for the query
$popular_post_args = array(
	'meta_key'  => 'post_views_count', //meta key currently set
	'orderby'    => 'meta_value_num', //orderby currently set
	'order'      => 'DESC', //order currently set
	'posts_per_page' => 5 // show no. of posts
);

//Initialise the Query and add the arguments
$popular_posts = new WP_Query( $popular_post_args );

if ( $popular_posts->have_posts() ) :
?>
	<ul>
		<?php
			while ( $popular_posts->have_posts() ) : $popular_posts->the_post();
			?>
			
				<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
			<?php
			endwhile;

			wp_reset_postdata();
		?>
	</ul>
<?php 
endif;

The post with the highest view counts will be on the top and rest are in order.

Leave a Reply

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