Track Post Views Without A Plugin–[WordPress]

Share & Comment

Wordpress Optimization Tips

If you want to track the individual post views for your blog to find out which posts are the most popular ones and also do not want to hit the performance of the blog by adding another plugin. You could do this with very easy code changes to your theme.

Open your theme’s ‘functions.php’  thesis theme users can add this code to ‘custom_functions.php’

Code Explanation

So what is this code doing. Let’s start with getPostViews and setPostViews functions are used to track the views for a post using custom field “post_views”  for the post. Function trackPostViews uses the wp_head hook to track the view when ever a post page is viewed. For this to work you theme should support wp_head hook. The last two functions will add a column on the wp-admin Posts screen as shown in the screen shot below.

wp post views without plugin

I am using the same tip to track Post Views on this blog.

Thanks for reading this article and keep your comments coming. Smile

Vijay Sharma

Vijay Sharma is an aspiring tech blogger and internet consultant focused on helping the community with the tips and tricks that can help you build better web business.

Comments

  1. Jonny says

    Hey Vijay, Im having trouble with this code. It’s incrementing the post_views value for the viewed post PLUS its next post. How do I stop this?

    I think it’s the update_post_meta() function that’s doing it. Very annoying! Any ideas?

  2. Jonny says

    Arrr ha! I found the fix… you may want to mention it here…

    It’s a bug/behaviour of Firefox’s, which pre-loads the next post (given in the rel=’next’ link tag in the header). This prev/next link in the header needs to be turned off for accurate page view data.

    For WordPress versions 3.0 and above:
    //remove auto loading rel=next post link in header
    remove_action(‘wp_head’, ‘adjacent_posts_rel_link_wp_head’);

    For older WordPress versions:
    //remove auto loading rel=next post link in header
    remove_action(‘wp_head’, ‘adjacent_posts_rel_link’);

    As found at:
    http://wordpress.org/support/topic/update_post_meta-updates-2-posts
    http://wordpress.org/support/topic/firefox-uses-headerphp-twice?replies=4