Placeholder canvas

How to Display Popular Posts by Views in WordPress

Would you like to see popular posts in WordPress sorted by their number of views? 

By displaying your most popular WordPress blog posts, you can make it easier for people to identify your greatest and most valuable content.

Additionally, it could entice visitors to stay on your website for more time, which is a good metric in the eyes of search engines like Google.

In the simple guide, I will demonstrate how to display popular posts by views in WordPress.

Let’s dive in without further ado!

Why Should You Display Popular Posts by Views in WordPress?

Enhancing user engagement is the site owner’s primary responsibility, and numerous strategies and tactics are available to help them achieve this goal.

One method is to display your site’s most popular post to visitors upfront. You can do this by placing the most popular posts in a sidebar or before the article’s conclusion.

The higher your user engagement rate, the more valuable Google considers your content to be. As a result, your website might appear higher in the search results.

Additionally, it provides readers more time to take action, like subscribing to your newsletter. Unfortunately, there isn’t a built-in WordPress feature or block that allows you to see your most popular posts ranked by number of page views.

But don’t worry.

I will walk you through how to accomplish that precisely using some basic coding.

Let’s go!

In the part below, I will be using the plugin WPCode. If you consider following along, ensure it is installed and activated first in your WordPress dashboard.

Refer to this guide for more help installing and activating a WordPress plugin.

How to Display Popular Posts by Views in WordPress

I chose the WPCode plugin because it allows you to insert custom code safely without dealing directly with your WordPress files. 

Additionally, as this approach requires several code snippets, the plugin will ensure you can easily manage and track them.

Step 1: Adding the WordPress Post-Views Counter Function

After activating the plugin, select Code Snippets > Add Snippet from the dashboard. Next, choose “Use snippet” while hovering over the option “Add Your Custom Code (New Snippet).”

You are currently in the code snippet editor for WPCode. Before adding any code, give the Snippet a title.

You may call this piece of code “WordPress Post Views Counter Function.” This is so that WordPress may have a function for counting post views, which is what the first code does.

Next, select “PHP Snippet” as the Code Type. Remember that you must add all the code from this post written in PHP.

You must copy and paste the code below in the empty field.

function custom_set_post_views($postID) {

    $count_key = 'custom_post_views_count';

    $count = get_post_meta($postID, $count_key, true);

    if(empty($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);

    }

}

// Remove prefetching to ensure accurate view counts

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

Simply choose “Auto Insert” for the Insert Method and “Run Everywhere” for the Location when you reach the “Insertion” section.

The good thing about this tool is that it auto-inserts the code in the theme’s functions.php file, so you don’t have to do it manually.

Next, choose the code by navigating to the upper right corner of the page.

Following that, select “Save Snippet.”

Let’s now move on to the next step.

Step 2: Tracking The Post Views 

At this point, you must add a new custom code snippet. This one can be called “Tracking The Post Views Function Call.”

This code will activate the function above on your single post pages by calling it.

After doing that, copy and paste the one-liner code given below:

wpb_set_post_views(get_the_ID());

Since this code is supposed to run on single post pages, you must select the location “Insert After Post.”

After that, you can simply make the code active by turning the toggle on and Saving the Snippet.

Step 3: Inserting WordPress Post Views Tracker

Now, you need to include a new code snippet. And this one will ensure that the current page is a single post.

If this Snippet finds the current page is a single post, it will call the WordPress Views Counter Function to track that post’s most recent view count.

So, whenever a viewer visits the page, its views will be updated.

You can conveniently name this Snippet something along the lines of “WordPress Post Views Tracker,” and for the code part, insert the one given below:

function custom_track_post_views ($post_id) {

    if ( !is_single() ) return;

    if ( empty ( $post_id) ) {

        global $post;

        $post_id = $post->ID;    

    }

    custom_set_post_views($post_id);

}

add_action( 'wp_head', 'custom_track_post_views');

You can select “Frontend Only” as the location and “Auto Insert” as the insert technique.

As we did with the previous code snippets, to save your progress, simply activate the code and save the sample.

Note: This method might not function by default if you are using a caching plugin. To make it work, you might leverage the fragment caching capability provided by some cache plugins, such as W3 Total Cache.

Step 4: Adding Functions to Fetch the Post View Count and Display the Most Popular Posts With View Counts

This straightforward guide is ending, but one last thing remains, which will be helpful when displaying the list of most viewed posts.

For this, you must add a code snippet that fetches the number of views for a specific WordPress post.

This code can be named “Fetching the Post Views Count Function” and set the location to “Run Everywhere.”

You will need the following code snippet:

function get_custom_post_views($postID){

    $view_key = 'custom_post_views_count';

    $view_count = get_post_meta($postID, $view_key, true);

    if($view_count==''){

        delete_post_meta($postID, $view_key);

        add_post_meta($postID, $view_key, '0');

        return "0 View";

    }

    return $view_count.' Views';

}

Turn on the toggle to activate it, and save the code snippet.

After that, create  and name the code snippet like “Display the Popular Posts with View Counts.”

This code will display your most well-liked blog entries at the bottom of your blogs.

Insert the following Snippet in the insert code field:

// Define query parameters

$popular_posts_query = new WP_Query( array(

    'posts_per_page' => 5, // Adjust as needed

    'meta_key' => 'wpb_post_views_count',

    'orderby' => 'meta_value_num',

    'order' => 'DESC'

));

?>

<div class="popular-posts">

    <h2>Explore Our Most Popular Content</h2> <!-- Customize the title -->

    <ul>

    <?php while ( $popular_posts_query->have_posts() ) : $popular_posts_query->the_post(); ?>

        <li>

            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

            - <?php echo wpb_get_post_views(get_the_ID()); ?>

        </li>

    <?php endwhile; ?>

    </ul>

</div>

<?php wp_reset_postdata(); ?>

You can tweak the number of posts that display at the end of your website or webpage.

Ensure you choose “Insert After Post” for the Location in the WPCode Insertion section. Simply activate the code and save the changes to ensure all your hard work reflects on your website.

Lastly, check to see if the code functions on one of your blog articles are all left to accomplish.

Conclusion:

I am confident that you can display popular posts by views in WordPress. Initially, it might seem a pretty complicated endeavor, but that’s barely the case as you start the process.

The plugin WPCode we used for this guide is pretty popular on the WordPress plugins store. It has a solid five-star rating and over 2 million active installations.

Displaying popular posts by views in WordPress has proven to increase user engagement, lower bounce rates, enhance content visibility, and increase engagement.

It is an endeavor truly worth pursuing!

FAQs:

How do I check if my code works without making permanent changes to the site?

You can use the WPcode’s testing mode to check if the code works without making permanent changes to the site.

Will displaying popular posts by views affect my website’s performance?

It depends on how you implement it. A well-coded plugin or custom code with efficient queries should not significantly impact your website’s performance. However, displaying popular posts with real-time view counts might require more resources than caching the view counts periodically.

How often should I update the list of popular posts by views?

It’s a good practice to update the list periodically to keep it relevant and engaging for your audience. You can set the frequency based on your website’s traffic and content update frequency. Some plugins offer options to update the list at specified intervals automatically.

Can I track the performance of popular posts displayed on my website?

Yes, you can track the performance of popular posts by views using various analytics tools such as Google Analytics. These tools provide insights into which posts attract the most traffic, helping you further optimize your content strategy. Additionally, some plugins may offer built-in analytics features.

Want faster WordPress?

WordPress Speed Optimization

Try our AWS powered WordPress hosting for free and see the difference for yourself.

No Credit Card Required.

Whitelabel Web Hosting Portal Demo

Launching WordPress on AWS takes just one minute with Nestify.

Launching WooCommerce on AWS takes just one minute with Nestify.