Home

Add a Visitor Counter to Your WordPress Blog

by David Pankhurst - Saturday Feb 5, 2005

IMPORTANT NOTE: This Article Has Been Updated

We all want to know how we’re doing, right? One of the first things everyone wants to put on their website is a counter. I still remember in the mid-90s trying to find code that would let me put a counter on my site, each and every page.

Of course, web logs today are quite detailed, and you really don’t need a counter, but in case the urge is just too much, here’s a quick and simple counter for your WordPress page:

  • Edit your blog’s index.php file, and look for a place in the php to add code � right after this entry is a good place to start:

    require('./wp-blog-header.php');

  • At that point, add this code function:
    function displayCounter()
    {
      // simple php counter - copyright (c) 2005 D.Pankhurst
      // (BigBizBlog.com) free to use - just please keep copyright in
      $counternum=dirname($_SERVER['SCRIPT_FILENAME'])."/counter.txt";
      $counter="";
      if ( $fp = @fopen($counternum,'r+') ) // success?
      {
        $counter = fgets($fp,9);
        $counter=$counter+1;
        rewind($fp);
        fputs($fp,$counter);
        fclose($fp);
      }
      echo $counter;
    }
    
  • Now look through your php code for a place to display your counter. When you have a spot, add this code to the html there:

    <?php displayCounter(); ?>

    (Note: leave off the <?php and ?> if you want to place the code in a php section).

  • Now create an empty text file, and call it counter.txt
  • Upload your modified index.php file and the new counter.txt file - for safety, back up the old index.php file first.
  • Change the permissions on your text file � if Unix, you want to CHMOD the file to 777.

Now when you load the main page, you’ll have a text display of how often the page has been viewed. Be warned � this will be anytime an article is looked at, not just a main page view.

The code can be made quite fancy, with as many bells and whistles as desired � but for a simple, easy to use WordPress counter, it’s a great way to plug one in fast.

3 Responses to “Add a Visitor Counter to Your WordPress Blog”

  1. web tasar Says:

    Thanks this is unique counter?

  2. David Pankhurst Says:

    No, it just displays a count for each page view, with repeated visits by the same person counting again.

    Also, be sure to use the latest, a WordPress counter plugin here:

    http://www.utopiamechanicus.com/37/wordpress-visitor-counter/

  3. Alex Says:

    I found your site on technorati and read a few of your other posts. Keep up the good work. I just added your RSS feed to my Google News Reader. Looking forward to reading more from you down the road!

Leave a Reply