Snippet: Track Views of Posts, Pages or Custom Post Types without Plugin

This snippet automatically track views of posts, pages and custom post types. You can use get_post_views function having optional $post_id parameter to fetch the number of views of any post, page or custom post type. You can also add “Views” column in admin panel for each post type.

Usage

echo get_post_views(get_the_ID()); 

Snippet

add_filter("wp_head", "wpds_increament_post_view");
function get_post_views($post_id=NULL){
    global $post;
    if($post_id==NULL)
        $post_id = $post->ID;
    if(!empty($post_id)){
        $views_key = 'wpds_post_views';
        $views = get_post_meta($post_id, $views_key, true);
        if(empty($views) || !is_numeric($views)){
            delete_post_meta($post_id, $views_key);
            add_post_meta($post_id, $views_key, '0');
            return "0 View";
        }
        else if($views == 1)
            return "1 View";
        return $views.' Views';
    }
}
function wpds_increament_post_view() {
    global $post;
    
    if(is_singular()){
        $views_key = 'wpds_post_views';
        $views = get_post_meta($post->ID, $views_key, true);
        if(empty($views) || !is_numeric($views)){
            delete_post_meta($post->ID, $views_key);
            add_post_meta($post->ID, $views_key, '1');
        }else
            update_post_meta($post->ID, $views_key, ++$views);
    }
}

Add Views Column In Admin

To add a column in “All Posts” screen in admin panel, use the following snippet.

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 get_post_views(get_the_ID());
}

Custom Post Types

Very Similarly, for any custom post type you just need to add action and filter call for your specific custom post type. For example, it will look like this for a “portfolio” post type.

add_filter('manage_portfolio_posts_columns', 'posts_column_views');
add_action('manage_portfolio_posts_custom_column', 'posts_custom_column_views',5,2);

Pages

WordPress Page is not a custom post type, Therefore, it require a different call.

add_filter('manage_pages_columns', 'posts_column_views');
add_action('manage_pages_custom_column', 'posts_custom_column_views',5,2);

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>