see also: TRBMostVisited

Page Hit Counter

version 0.6

The idea

Let's count how many users read each page, so that we know what we should focus on!

The details

This is a page hit counter, that counts how many people visit each of the pages at your Wikka-powered site. Installation requires adding some files and involves some small changes in two or three others as well as slight addictions to database structure.
This code is based on GmBowenCounter. Since the time when that original version was made, many things in Wikka code changed, hence I made this version so that those who don't feel strong enough in PHP can still benefit from a counter. This version also adds a lot of functionality.

How it works


This version is compatible with the original GmBowenCounter in terms of counter action syntax. However it's not so with database structure. Namely, the meaning of hits field in _pages table is changed. It used to be "total hits for that page", while now it is "hits for that page since last edit". Hence, to get total hits in this version it's necessary to sum up hits values of all revisions of a page. The advantage is that now we could see how many hits did each revision have (this is planned for my version of MostVisited action) Also this new approach doesn’t require altering of Wakka class. If you need a version that counts the old way, get TRBCounter version 0.3 (which is unfortunately not compatible with Wikka prior to

The original MostVisited by George Petsagourakis works fine with this code, since it seems it already expects data the way TRBCounter 0.4 (and newer) counts it.
This has been tested with Wikka and

What's new in this version

0.6 (since TRBCounter 0.5)

0.5 (since TRBCounter 0.4)

0.4 (since TRBCounter 0.3)

0.3 (since TRBCounter 0.2)

0.2 (since TRBCounter 0.1)

0.1 (since the original release by GmBowen)


Instructions -- how to set up a counter in your Wikka-powered site

1. Update your database schema

The xx_pages table has to have the following fields added (note that xx_ should be substituted with your prefix):


ALTER TABLE `xx_pages` ADD `last_visited` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00';

If you don’t intend to use “last visited” functionality, you may omit the second one.

2. Create a file counter.lib.php

Create a file libs/counter.lib.php (feel free to choose a different location and update the file footer.php accordingly -- see point 6. below).

// Let's grab the setting
$showcounter = strtolower($this->GetConfigValue('show_page_hit_counter'));
if ($showcounter == '') $showcounter = 'disabled';

if ($showcounter != 'disabled') {

    // Let's prepare a list of PageNames that should have counter disabled
    $disable_pages = explode(',',strtr($this->GetConfigValue('page_hit_counter_disable_pages'), array(" " => "")));

    // Let's delete possible empty entries
    foreach ($disable_pages as $i => $v) if ($v == '') unset($disable_pages[$i]);

    // If this page is blacklisted, disable counter
    if (array_search($pagetag, $disable_pages)) $showcounter = 'disabled';
// If the counter isn't off and we are allowed to read the page, proceed...
if (($showcounter != 'disabled') && ($this->HasAccess('read')))
    // Get hit count
    $result = $this->Query( "SELECT SUM(hits) AS hits FROM ".$this->config["table_prefix"]."pages WHERE tag='$pagetag'");
    $row = mysql_fetch_array($result);
    $hit_count = $row['hits'];

    // Let's prepare a list of UserNames that shouldn't increment the counter.
    $ignore_users = explode(',',strtr($this->GetConfigValue('page_hit_counter_ignore_users'),array(" " => "", "'" => "")));
    // Let's remove incorrect names.
    foreach ($ignore_users as $i => $v) if (!$this->IsWikiName($v)) unset($ignore_users[$i]);

    // Let's add current user.
    array_push($ignore_users, $this->GetPageOwner($tag));

    // For compatibility with Wikka 1.1.6.x
    if ($this->method != '') $this_handler = $this->method; else $this_handler = $this->handler;
    if (method_exists($this,'GetCookie')) $this_cookie = $this->GetCookie("TRBCounter".$pagetag); else $this_cookie = $this->GetWikkaCookie("TRBCounter".$pagetag);

    // Counter is incremented if currently logged user in not in $ignore_users
    // We check if handler == show to prevent counter from being incremented while viewing page's history.
    // We only increment while viewing latest revision (older revisions are probably being viewed by editors).
    // We only increment if the cookie is not set.
    if ((($this_handler == 'show') && ($this->page['latest'] == 'Y') && (!array_search($this->GetUserName(), $ignore_users))) && !$this_cookie)
        $this->Query("UPDATE `".$this->config["table_prefix"]."pages` SET `hits` = `hits` + 1 WHERE tag='$pagetag' AND latest='Y'") or die("Unable to process query: " . mysql_error());
        // Creating a cookie to make counter reload-proof (6 hours)
        // USING SetPersistentCookie FOR COMPATIBILITY WITH 1.1.6.x
        // Should we update the last_visited value?
        if ($this->GetConfigValue('page_hit_counter_last_visited_enable'))
            $this->Query("UPDATE `".$this->config["table_prefix"]."pages` SET `last_visited` = NOW() WHERE tag='$pagetag' AND latest='Y'") or die("Unable to process query: " . mysql_error());

    // Should we display the counter?
    if (($showcounter !='off' && $showcounter !='owner') or ($showcounter =='owner' && $this->GetUserName() == $this->GetPageOwner($tag)))
        // Yes, let's see if the translation is available
        if (!defined('PAGE_HIT_COUNTER')) define('PAGE_HIT_COUNTER','Total hits: %s');
        // Start output of counter
        echo (":: <span class=\"counter\">"); echo sprintf(PAGE_HIT_COUNTER,"<span class=\"hits\">".$hit_count."</span>"); echo ("</span>");

3. Create an action file counter.php in a proper place

For an unstable Wikka this will be actions/counter/counter.php.
For Wikka 1.1.6.x this will be actions/counter.php.

switch(strtolower($show)) {
    case 'disabled':
    case 'disable':
    case 'off':
    case 'no':
    case 'owner':
if ($ignore != '') $this->SetConfigValue('page_hit_counter_ignore_users',$ignore);

4. Create an action file nocounter.php in a proper place (optional)

If you keep your counter enabled globally, and wish to have the possibility to easily disable it, create an action file nocounter.php.
For an unstable Wikka this will be actions/nocounter/nocounter.php.
For Wikka 1.1.6.x this will be actions/nocounter.php.


Writing {{nocounter}} is exactly the same as {{counter show="disable"}} just shorter.

5. Reverting changes in Wakka class and edit handler

This section is only for people upgrading from GmBowenCounter or TRBCounter version prior to 0.4.

In previous versions of this add-on you were advised to make some changes to your edit handler and Wakka class. Now you need to revert them to originals.

5a. Reverting edit.php handler
In an unstable Wikka open a file handlers/edit/edit.php. In Wikka open a file handlers/page/edit.php. Search for a line:
$this->SavePage($this->tag, $body, $note, $this->page['hits']);

and change it to:
$this->SavePage($this->tag, $body, $note);

It should be in line number 130 ( or line number 133 (

5b. Reverting the Wakka class
Open a file libs/Wakka.class.php and search for function SavePage. In my unstable Wikka it is around line 1867. In official it is in line 608.
function SavePage($tag, $body, $note, $pagehits)

function SavePage($tag, $body, $note)

Just a few lines below find the line:
hits    = '".mysql_real_escape_string($pagehits)."',

and delete it.

6. Add the code to your footer.php

For an unstable Wikka and Wikka this will be templates/footer.php.
For Wikka this will be actions/footer.php.
Search for:
<?php echo $this->FormClose(); ?>

and above it add:
<?php require_once($_SERVER["DOCUMENT_ROOT"].'libs/counter.lib.php'); ?>

7. Add translation for the 'Total hits' text (Wikka >= only) (optional)

Open lang/xx/ (substitute xx for a code of your language). Search for a line beginning with define('SEARCH_LABEL', and add the following line below it:
define('PAGE_HIT_COUNTER', 'Total hits: %s');

...of course replacing Total hits with your translated text. The symbol %s will be replaced by a number.

8. Add a global counter settings (optional)

Open wikka.config.php and add the following lines:
'show_page_hit_counter' => 'on',

This will globally set your counter on/off and display/hide it. Instead of 'on' you can use 'off' or 'owner'. The default is 'disabled'.

'page_hit_counter_ignore_users' => 'UserName1, UserName2',

This will set usernames that shouldn't increment the counter. It doesn't influence if counter is displayed. You can override this setting by using action's counter parameter ignore="".

'page_hit_counter_disable_pages' => 'PageIndex, RecentChanges, RecentlyCommented, MostVisited, UserSettings, TextSearch, TextSearchExpanded',

This will disable counter on the pages listed above. Customize your list as desired.

'page_hit_counter_last_visited_enable' => 'true',

This will turn on recording of a date and time of last visit.

9. Edit your wikka.css file (optional)

You may change the way a counter is displayed on page, by adding lines to css/wikka.css, for example like this:
.counter {font-size: smaller;} /* influences whole counter text */
.counter .hits {font-weight: bolder;} /* influences just the number */

Please test and give feedback. Regards, --KrzysztofTrybowski

There are 4 comments on this page. [Show comments]
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki