I'm making a plugin that counts the number of times a visitor visits my site. I want to run the code in the plugin once per page load. What's a good action hook I can use ?


Basic idea is to use javascript to make an AJAX call back to the site which in turn save the hit because if you use PHP alone, then hits for cached pages won't be counted because no PHP is processed at that time.

Study the code of WP-Postviews plugin http://lesterchan.net/portfolio/programming/php/#wp-postviews


Hook may be fired twice in Firefox because it prefetches URL specified in HTML source as

<link rel='next' href='http://www.domain.com/adjacent-post/' />

Use this to remove that line from source

remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');

  • I'm saving the hits in a database. Every page refresh saves a 'hit'. The problem is, the hits are increasing by 2 for every page load. This is because the action i'm using is being fired off twice. – 21zna9 Nov 14 '11 at 22:32
  • @Ankur I have modified the answer – Ashfame Nov 15 '11 at 0:46
  • I applied this and it seemed to do the trick. Would it be better if I use the init action? – 21zna9 Nov 15 '11 at 3:50

@Ashfame is right with what he wrote. About your hook (we don't know which one you're using - firing twice sounds strange): shutdown is the last hook executed.


The way I would do it is not using any hooks at all. Just because Wordpress provides action and filter hooks does not mean you have to use them. In your footer.php file, add the following before the tag.

<?php if ( is_single() )  registerHit(get_the_ID()); ?>

Then in your functions.php add this function:

function registerHit($post_ID)
    $meta_key = 'post_views_count';
    $count = get_post_meta($post_ID, $meta_key, true);
    if( $count == '')
        $count = 0;
        delete_post_meta($post_ID, $meta_key);
        add_post_meta($post_ID, $meta_key, '0');
        update_post_meta($post_ID, $meta_key, $count);

Some would argue that this is too manual for Wordpress, but I've been using Wordpress for years, I use it on every single project I basically work on and sometimes it's easier to use a straight up function as opposed to using an action or filter.

  • The thing is I hate meta keys. I hate having my writers look at anything that's not default, because it confuses them. I also have to deploy this functionality on over 300 blogs. That's why I made this into a plugin. – 21zna9 Nov 15 '11 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.