Display Popular Posts by Views in WordPress without a Plugin

If you don't have comments on a post then how to order post by popularity? Why not order it by view count with a simple hack!

By default WordPress does not allow to show or order post by views, so we have to use a little trick which can make our blog a much more lively.
So let get started, first, we 'll create a custom post meta as whpp_track_post_views, then on every post visit we have to increase the counter by one.

<?php

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

add_action('wp_head', 'whpp_track_post_views');

function whpp_set_post_views($post_id) {
    $count_key = 'whpp_track_post_views';
    $count = get_post_meta($post_id, $count_key, TRUE);
    if ($count == ") {
        $count = 0;
        delete_post_meta($post_id, $count_key);
        add_post_meta($post_id, $count_key, '0');
    } else {
        $count++;
        update_post_meta($post_id, $count_key, $count);
    }
}

// To keep the count accurate, lets get rid of prefetching
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

USAGE
Now that we have set the custom post meta we need to add following code in WP_Query to short post my view

<?php
$args = [
//…
'meta_key' => 'whpp_track_post_views',
'orderby' => 'meta_value_num',
'order' => 'DESC',
//…
];

$query = new WP_Query($args);

//…
//…

Some of the related question in StackOverflow, which might come handy:
Raunak Gupta

Raunak Gupta

I'm Raunak Gupta, a seasoned software developer with over 9 years of experience in a wide range of programming languages, frameworks, and tools. I started my journey as a WordPress & CakePHP developer in 2014, diving deep into the world of OOPs, Request handling, and SEO. Along the way, I crafted numerous dazzling WooCommerce stores, tamed payment gateways, optimized for full filament functionality, and achieved ultra-low latency for lightning-fast load times. My expertise extends to BI tools, website builders, DevOps, and team leadership. I like to help upcoming developers, so I share my experience through this blog and by assisting fellow developers on Stack Overflow, where I've earned a stellar reputation with over 10k+ points of recognition.

Articles: 29

4 Comments

  1. I don’t normally comment, but I gotta tell ya, appreciate it for the post on this bonza one, mate! 😀

Leave a Reply

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