Support » Plugins » Hacks » Hit counter increases by 2

  • Hi,

    I’m having a hard time with a hit counter implemented for a WordPress site. I have this in my functions.php (also tried in the footer directly):

    function get_counter() {
    $count_my_page = get_template_directory()."/widgets/hitcounter.txt";
    $hits = file($count_my_page);
    if (is_page_template('front-page.php')) {
    	$hits[0] ++;
    	$fp = fopen($count_my_page , "w");
    	fputs($fp , "$hits[0]");
    return $hits[0];

    I have tested with the IF condition and without. The file gets open, read, incremented for the front-page, saved and shown correctly. However, it seems to reopen and resave another time on the back-end (or where ever it is) because the value has been incremented 2 times in the file (though it displays correctly with 1 increment). I tested the code in a PHP clean installation (without WordPress) and it works fine. It seems like its something with WordPress only. Anyone noticed this behaviour?

    I can’t seem to find a solution to this. My client clearly asked for a front page view counter and I have to fix this.

    EDIT: I’ve noticed it only happens when logged in on WordPress. If not logged in, the counter is working as normal.


Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz


    WP does mysterious things with file access. I’ve no doubt the template or where ever you have the function call is really accessed twice, so in a sense, the counter is accurate.

    You could try hooking an action that yields the proper results instead of calling from a template. See Plugin API/Action Reference.

    If all else fails, you could make a similar function that decrements the counter that only fires on an admin action to correct the double increment from the template. Ugly, but if it works…

    Fortunately, we are using WordPress as a site, not a blog and do not allow users (except for our clients and admins). This should not occur often and thus, we will not fix for now.

    You might have some good points. Might be worth a look if we need it later on. Thanks.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Hit counter increases by 2’ is closed to new replies.