This simple snippet tracks and shows WordPress post views in your templates – and without the need for a plugin.

Instructions
Add this to your functions.php file.

// function to display number of posts.
function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}

// function to count views.
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($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);
    }
}


// Add it to a column in WP-Admin
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
   if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

Add this to your single.php, and make sure you paste in inside the loop.

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

To display the number of views a post has, just add this in your template where you want the post view count to be displayed.

<?php echo getPostViews(get_the_ID()); ?>

 

Related Links:
http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/

Comments

  1. Thanks a lot. The code snippet really worked like charm! It’s showing page views accordingly and very fast in updating the views too

Leave a Reply

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

Contact Us

This could be the beginning of something great 🙌

"*" indicates required fields

Name*
Hidden
Hidden

By submitting this form: You agree to the processing of the submitted data in accordance with WP Dynamics Privacy Policy.

Contact Information
You can also write us an email or contact us by telephone.
Telephone +45 71 74 71 21

Support For support inquiries, please refer to our support section.

Recent Articles

Faust.js – A Headless Framework for WordPress

Faust.js is a Headless WordPress Framework that provides a set of tools for building front-end applications based on WordPress ...

How to Load (Enqueue) and Handle Assets and Dependencies in WordPress

In WordPress, instead of adding assets such as styles and JavaScript to the header, you can and should use ...

An Introduction to Google Tag Manager Server-side Tagging

WordPress has come a long way since its launch in 2003 - from a blogging tool to a full-fledge ...