Home / Admin / Post Views Count | Post Views Tracking with Shortcode and Admin Column and Elementor Support
Duplicate Snippet

Embed Snippet on Your Site

Post Views Count | Post Views Tracking with Shortcode and Admin Column and Elementor Support

This WordPress code provides a comprehensive solution for tracking post views. It includes: cookie-based view counting to prevent duplicates, a [post_views] shortcode for front-end display, and a "Views" column in the admin area, which is sortable for easy overview. It also displays post views in the admin bar when viewing single posts.

✨ Additionally, it supports Elementor Pro — just set the Query ID to 'views_sort' in any Posts or Loop Grid widget to display your most viewed posts first.
Want to show trending posts ticker?

You can get the snippet "WordPress Trending Posts | Popular Posts Ticker Shortcode" from Snippets Library.

Code Preview
php
<?php
/*
Description: 
Enhance your WordPress site with a post view tracking system. This snippet uses a one-hour cookie to avoid inflating counts, offers a get_post_views() function for developers, a [post_views] shortcode for users, and adds a sortable "Views" column to your post list in the admin.
Key elements covered in these descriptions:
✨ Core Functionality: Tracking post views. metakey "post_views_counting"
✨ Prevention of Duplicate Counts: Creates a cookie for 1 hour to avoid multiple counting from current user.
✨ Display Options: Shortcode [post_views] for front-end, sortable column in admin.
✨ Additionally, it supports Elementor Pro — just set the Query ID to 'views_sort' in any Posts or Loop Grid widget to display your most viewed posts first.
✨ Show view count in admin bar.
✨ Ease of Use: Simple implementation.
✨ Benefits: Understanding content popularity, tracking engagement.
Want to show trending posts ticker? 
You can get the snippet "WordPress Trending Posts | Popular Posts Ticker Shortcode" from Snippets Library.
*/
// Function to track post views
function track_post_views($post_id) {
    if (!is_single() || (is_user_logged_in() && current_user_can('manage_options'))) {
    return;
	}
    
    $key = 'post_views_counting';
    $current_views = get_post_meta($post_id, $key, true);
    $current_views = $current_views ? $current_views : 0;
    
    // Prevent multiple views in a short period
    $cookie_name = 'post_viewed_' . $post_id;
    if (!isset($_COOKIE[$cookie_name])) {
        setcookie($cookie_name, 'true', time() + 3600, '/'); // Expires in 1 hour
        update_post_meta($post_id, $key, $current_views + 1);
    }
}
// Hook into WordPress template
function track_views_on_single_post() {
    if (is_single()) {
        global $post;
        track_post_views($post->ID);
    }
}
add_action('wp', 'track_views_on_single_post');
// Function to display view count
function get_post_views($post_id) {
    $key = 'post_views_counting';
    $views = get_post_meta($post_id, $key, true);
    return $views ? $views : 0;
}
// Shortcode to display post views
function post_views_shortcode($atts) {
    global $post;
    return get_post_views($post->ID);
}
add_shortcode('post_views', 'post_views_shortcode');
// Add post views column to admin
function add_views_column($columns) {
    $columns['post_views'] = 'Views';
    return $columns;
}
add_filter('manage_posts_columns', 'add_views_column');
function display_views_column($column_name, $post_id) {
    if ($column_name === 'post_views') {
        echo get_post_views($post_id);
    }
}
add_action('manage_posts_custom_column', 'display_views_column', 10, 2);
// Make the 'Views' column sortable
add_filter('manage_edit-post_sortable_columns', function($columns) {
    $columns['post_views'] = 'post_views_counting'; // 'post_views' is column ID, 'post_views_counting' is meta_key
    return $columns;
});
// Sort by post_views_counting meta key
add_action('pre_get_posts', function($query) {
    if (!is_admin() || !$query->is_main_query()) return;
    if ($query->get('orderby') === 'post_views_counting') {
        $query->set('meta_key', 'post_views_counting');
        $query->set('orderby', 'meta_value_num');
    }
});
//Show in admin bar
add_action('admin_bar_menu', 'mb_add_post_views_to_admin_bar', 100);
function mb_add_post_views_to_admin_bar($admin_bar) {
    if (!is_admin() && is_singular()) {
        global $post;
        if (!$post instanceof WP_Post) return;
        // Optional: Restrict to users who can edit posts
        if (!current_user_can('edit_post', $post->ID)) return;
        $views = get_post_meta($post->ID, 'post_views_counting', true);
        $views = $views ? $views : 0;
        $admin_bar->add_node([
            'id'    => 'post_views_count',
            'title' => '👁 Views: ' . number_format_i18n($views),
            'meta'  => ['title' => 'This post has been viewed ' . number_format_i18n($views) . ' times']
        ]);
    }
}
// Only run this if Elementor Pro is active
function mb_add_post_views_sorting_for_elementor() {
    // Check if Elementor is loaded and the required function exists
    if ( ! did_action('elementor/loaded') || ! function_exists('elementor_pro_load_plugin') ) {
        return;
    }
    // Add the custom query handler
    add_action('elementor/query/views_sort', function($query) {
        $query->set('meta_key', 'post_views_counting');
        $query->set('orderby', 'meta_value_num');
    });
}
add_action('init', 'mb_add_post_views_sorting_for_elementor');
// Function to track post views
function track_post_views($post_id) {
    if (!is_single() || (is_user_logged_in() && current_user_can('manage_options'))) {
    return;
	}
    
    $key = 'post_views_counting';
    $current_views = get_post_meta($post_id, $key, true);
    $current_views = $current_views ? $current_views : 0;
    
    // Prevent multiple views in a short period
    $cookie_name = 'post_viewed_' . $post_id;
    if (!isset($_COOKIE[$cookie_name])) {
        setcookie($cookie_name, 'true', time() + 3600, '/'); // Expires in 1 hour
        update_post_meta($post_id, $key, $current_views + 1);
    }
}
// Hook into WordPress template
function track_views_on_single_post() {
    if (is_single()) {
        global $post;
        track_post_views($post->ID);
    }
}
add_action('wp', 'track_views_on_single_post');
// Function to display view count
function get_post_views($post_id) {
    $key = 'post_views_counting';
    $views = get_post_meta($post_id, $key, true);
    return $views ? $views : 0;
}
// Shortcode to display post views
function post_views_shortcode($atts) {
    global $post;
    return get_post_views($post->ID);
}
add_shortcode('post_views', 'post_views_shortcode');
// Add post views column to admin
function add_views_column($columns) {
    $columns['post_views'] = 'Views';
    return $columns;
}
add_filter('manage_posts_columns', 'add_views_column');
function display_views_column($column_name, $post_id) {
    if ($column_name === 'post_views') {
        echo get_post_views($post_id);
    }
}
add_action('manage_posts_custom_column', 'display_views_column', 10, 2);
// Make the 'Views' column sortable
add_filter('manage_edit-post_sortable_columns', function($columns) {
    $columns['post_views'] = 'post_views_counting'; // 'post_views' is column ID, 'post_views_counting' is meta_key
    return $columns;
});
// Sort by post_views_counting meta key
add_action('pre_get_posts', function($query) {
    if (!is_admin() || !$query->is_main_query()) return;
    if ($query->get('orderby') === 'post_views_counting') {
        $query->set('meta_key', 'post_views_counting');
        $query->set('orderby', 'meta_value_num');
    }
});
//Show in admin bar
add_action('admin_bar_menu', 'mb_add_post_views_to_admin_bar', 100);
function mb_add_post_views_to_admin_bar($admin_bar) {
    if (!is_admin() && is_singular()) {
        global $post;
        if (!$post instanceof WP_Post) return;
        // Optional: Restrict to users who can edit posts
        if (!current_user_can('edit_post', $post->ID)) return;
        $views = get_post_meta($post->ID, 'post_views_counting', true);
        $views = $views ? $views : 0;
        $admin_bar->add_node([
            'id'    => 'post_views_count',
            'title' => '👁 Views: ' . number_format_i18n($views),
            'meta'  => ['title' => 'This post has been viewed ' . number_format_i18n($views) . ' times']
        ]);
    }
}

Comments

Add a Comment