Track Post Views & Sort by Most Popular

This tutorial will cover how to track post views using post meta in WordPress, without the need for an additional plugin. Using this tracking data, we can sort our posts by most popular. Let's get started.

Step 1

Add this code snippet to your theme's functions.php file, or by using a plugin like Code Snippets.

function set_post_views($postID) {
    session_start();
    // Define the post meta field
    $count_key = 'post_views_count';
    // Get the post meta field
    $count = get_post_meta($postID, $count_key, true);
    // If the count is blank
    if($count==''){
        // Set the count to 0
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    } else {
    if(!isset($_SESSION['post_views_count-'. $postID])){
        $_SESSION['post_views_count-'. $postID]="si";
        // Increment the count by one
        $count++;
        update_post_meta($postID, $count_key, $count);
        }
    }
}
//Remove prefetching to keep the count accurate
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); 

When this function runs, it increments the post_views_count meta value by 1. It also creates a session, so the visitor is only counted once per post, even if they refresh the page.

Step 2

Now we need to run this function. Just place this code within your singular post template or custom post type template, wherever you need to track views.

<?php set_post_views(get_the_ID()); ?>

Step 3

Now that we're tracking post views, we can sort our posts by most popular. We need to add some parameters to our query.

'orderby'    => 'meta_value_num',
'meta_key'   => 'post_views_count',
'order'      => 'DESC'

Where you add these parameters will differ depending on the theme or page builder you're using.

Example

I will show an example using Oxygen Builder. In this example, I've set up a custom post type called 'Portfolio'. I then followed steps 1 & 2 of this tutorial to implement view tracking.

To show the post view count on my portfolio template, I've added the following code.

<p>Post Views: <?php echo get_post_meta( get_the_ID(), 'post_views_count', true ); ?></p>

Now I want to show the 3 most popular posts on my portfolio template. I've added an Oxygen Repeater Element to my template, and set the following manual query.

post_type=portfolio&orderby=meta_value_num&meta_key=post_views_count&order=DESC&posts_per_page=3&no_found_rows=true

And that's it! With a little CSS styling, I have a "Most Popular Posts" feed displayed on my portfolio template.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments