Display Most Popular Post Without Using Plugin in WordPress

Sumit Singh
3 Jun 2022

There are numerous plugins available on the WordPress plugin directory for most popular posts. We are going to display the most popular post using the simple post query based on post views. We will be using post Meta to store the views count and weโ€™ll fetch the posts according to the views count using the stored Meta value. Sounds confusing but itโ€™s easier to implement.

Itโ€™s not that hard. Adding a few lines of code on Snippets for Oxygen Or other pagebuilder in theme functions.php and modifying our template file will be enough.

Install and activate Code Snippets plugin.

Go to Snippets > Add New.

function count_post_visited() {
    if( is_single() ) {
        global $post;
        $views = get_post_meta( $post->ID, 'post_viewed', true );
        if( $views == '' ) {
            update_post_meta( $post->ID, 'post_viewed', '1' );   
        } else {
            $views_no = intval( $views );
            update_post_meta( $post->ID, 'post_viewed', ++$views_no );
        }
    }
}
add_action( 'wp_head', 'count_post_visited' );

Thereafter, paste the following wherever in your template files that you wish to display the popular posts:

$popular_posts_args = array(
    'posts_per_page' => 5,
    'meta_key' => '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();

If you have any question then feel free ask me ๐Ÿ™‚

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy