Track and Display Post Views without Using a Plugin – WordPress

Advertisement

This simple snippet simply display and track post or page view in your site, this is helpful when you want to track post views of your site page and I want to share you how easy to do and apply in your site.

PHP

Add this PHP script in your functions.php file of your theme, or if you don’t have one, please create and copy and paste the script bellow.


function set_post_views( $postID )
{
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        // delete old 'post_views_count' value.
        delete_post_meta( $postID, $count_key );
        // add new 'post_views_count' value.
        add_post_meta( $postID, $count_key, '0' );
    } else {
        $count++;
        // update old 'post_views_count' value.
        update_post_meta( $postID, $count_key, $count );
    }
}

function get_post_views( $postID )
{
    $count_key = 'post_views_count';
    $count = get_post_meta( $postID, $count_key, true );
    if($count=='') {
        // delete old 'post_views_count' value.
        delete_post_meta( $postID, $count_key );
        // add new 'post_views_count' value.
        add_post_meta( $postID, $count_key, '0' );

        return "0 View";
    }

    return $count.' Views';
}

Confuse?

Ok let’s enumerate further the two functions above.

  • set_post_views: This function set or create number of post view into post meta of your post.
  • get_post_views: This function simply gets the number of post we set in set_post_views and return or display the result.

How to use the function?

Step 1:

Place this snippet within your single.php file inside the loop.


set_post_views (get_the_ID());

Step 2:

Just place this snippet below set_post_views() in your single.php file of your theme, where you want the post views to display.


echo get_post_views (get_the_ID());

That’s it, hope you like this tutorial.

Advertisement