WordPress.org

Ready to get started?Download WordPress

Forums

Hit counter increases by 2 (3 posts)

  1. SpiritOfTheWinds
    Member
    Posted 1 year ago #

    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]");
    	fclose($fp);
    }
    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.

    Thanks

  2. bcworkz
    Member
    Posted 1 year ago #

    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...

  3. SpiritOfTheWinds
    Member
    Posted 1 year ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic