In: , , , ,
On: 2004 / 09 / 17
Shorter URL for this post: http://ozh.in/2a

You have a blog. You have stats telling you how many people read it. You post links. But do you have something telling you how many people click on your links ?

Here is it : I'm releasing my latest plugin, Click Counter. Basically, it adds a click counter to links in your posts, as in these examples :
I love WordPress, WordPress and WordPress.
Click on one link and reload the page (hit counter displayed on mouseover link title, in plain text, or both)

Less basically, it comes with a real bunch of options you'll probably never need to tweak, but I wanted to do something as flexible and usable as I could.

Current version : 1.02

Note : you may find sometimes this plugin disabled here on my own server, when I'm tweaking a few things. The plugin is fully functionnal anyway, download it :-)

Note: The plugin is rather well commented, advanced users can probably directly download, edit and run. I'd suggest reading the "How it works" and "Tips & Tricks" sections anyway.

Set up the MySQL table

You need a new table in your WordPress database, named wp_linkclicks (you can modify the name, be sure then to edit the beginning of the plugin properly) Create this table with the following query :

  1. CREATE TABLE `wp_linkclicks` (
  2.  `link_id` INT NOT NULL AUTO_INCREMENT ,
  3.  `link_url` TEXT NOT NULL ,
  4.  `link_clicks` INT NOT NULL ,
  5.  `link_date` DATETIME NOT NULL ,
  6.  `link_title` TEXT NOT NULL ,
  7.  UNIQUE (
  8.   `link_id`
  9.  )
  10. );

Newbie tips : first, install PHPMyAdmin on your website. This is a great interface for anything you can do with MySQL databases. Once it's done, look for the "SQL" link in the menu : click, and paste in the textbox the above code. It will set up the required table for you.

Install

Download the plugin :
ozh-click-counter.zip
Extract and upload to your blog, preserving directory structure if any.
Note: download counter here and stats on wordpress.org may differ and reflect the number of downloads before this plugin was hosted on the plugin directory

The archive contains the tracker file, go.php : put this file in your blog root. If for some reason you want to modify the tracker file name, be sure to properly edit the beginning of the plugin script as well.

Use the plugin

In its default configuration, the plugin needs nothing more. Get back to your blog and post as usual. It will silently add trackers to links in your posts and links in commenters' posts.

A small warning : adding a counter to a link "costs" one SQL query. If you are hosted on a slow server, or if you are teh ultimate linkblogger with 200 external links posted in your frontpage à la Metafilter, you might slightly overload your SQL server :) If this is your case, read by the end of this article the Tips & Tricks, I'll explain how to add a "silent tracker with no SQL query".

Another small warning : the plugin works with proper xhtml syntax, that is href="url" or class="myclass" (quotes), not href=url or class=myclass (no quotes)

How it works

Don't change anything to your posting habits, the plugin is the "install & forget" type.

When your WordPress will print a post with a link, the plugin replaces every link target and title. For example :

  1. <a href="http://www.link.com/page.php">link</a>

becomes

  1. <a href="yourblog/go.php?http://www.link.com/page.php"
  2.  title="XX clicks">link</a>

The number of clicks in the title value will be added to an existing title if specified : title="this is a cool link (XX clicks)"

When someone clicks on this modified link, it will add or update the following values to the table you've created earlier :

  • link_id: the link id, which is more or less useless
  • link_url : the url, "http://www.this-is-a-link.com/page.php" in the above example
  • link_clicks : how many people clicked on it
  • link_date : the date of the first click on it (not the date you posted it)
  • link_title : the title of the remote page, if exists, as defined by its title html tag

Unless stated otherwise, only external links will have a counter added, because it's pointless to track how many people click on your pages. There are stats plugins for this :)
So, if you want to add a counter to an internal file, put a absolute path in the link html : href="http://site/blog/file" instead of href="file"

Template Tags

I've written two "template tags" you can add to your pages

  • wp_ozh_click_topclicks($limit, $trim , $pattern) : displays your most clicked links
  • wp_ozh_click_comment_author_link() : a replacer for comment_author_link() in wp-comments.php, if you want to add a counter to your commenters' website when specified.

As you can see, the first one, wp_ozh_click_topclicks, has 3 optionnal arguments :

  • $limit : how many links you want to display. Default value is 5, and can be modified in the plugin.
  • $trim : maximum length for displayed links title. Setting this for example at 5 will convert "WordPress Home" to "Wordp…". Default value is 15, and can be modified in the plugin.
  • $pattern : html code used to display the list. See right below.

The pattern parameter is an html string with template tags. The default value, as defined in the plugin, is :

  1. <li>
  2.   <a href="%%link_url%%" title="%%link_title%%">%%link_title_trim%%</a>: %%link_clicks%%
  3. </li>

Tags are enclosed in between "%%" and can be :

  • link_id: the link id number in the sql database, I don't see why you would use this one :)
  • link_url : the link url, obviously.
  • link_clicks : the number of clicks the link has received so far
  • link_date : date of first click (more or less useless too, I admit)
  • link_title : remote page title
  • link_title_trim : shortened value of link_title, trimmed to the value of $trim as defined previously.

If the target page has no title, and is html content, the title will be replaced by the url itself. In this case, %%link_title%% will output the url, shortened by its trailing slash and leading http://www. if applicable.

It the page has no title because it's not an html document (http://site.com/somefile.zip for example), it will be replaced by the document name (somefile.zip)

Optionnal configuration tweaking

Now, I'll go through all the variables and their default values you can modify and edit at the beginning of the script. For the interested only, most users don't need so much tweaking and are probably bored of reading this page :)
Note : as usual, I've named the plugin file, functions and vars with a beginning "wp_ozh_click" to prevent any nuclear world war.

Core variables :

$wp_ozh_click['table'] = 'wp_linkclicks'
Name of the table where stats will be stored

$wp_ozh_click['file'] = get_settings('siteurl') . "/go.php"
Name and location of the tracker file

Basic features :

$wp_ozh_click['track_all_links'] = 1
Value can be 1 or 0
If set to 1, every link will have a tracker. Just post as usual.
If set to 0, you will have to specify when you want to add a tracker, with the following code :

  1. <a href="http://site.com/" count="1">link</a>

The value countwill be removed at processing time, so output will be valid html.
The value of count can be : 1, title, inline, or a mix.

  • count = "1" : number of hits will be added to link according to the default behaviour as defined in the script (see below)
  • count = "title" : number of hits added in link title : <a href="http://site.com/" title="69 hits">link</a>
  • count = "inline" : number of hits added in plain text, after the link : <a href="http://site.com/" >link</a> (69 hits)
  • count="title inline" : both : <a href="http://site.com/" title="69 hits">link</a> (69 hits)

$wp_ozh_click['in_title'] = 1
Value can be 1 or 0
Default behaviour for displaying counter (according to $wp_ozh_click['track_all_links'] or to count value in the link html). If set to one, display hit number in link title.

$wp_ozh_click['in_plain'] = 0
Value can be 1 or 0
Default behaviour for displaying counter (according to $wp_ozh_click['track_all_links'] or to count value in the link html). If set to one, display hit number in plain text after the link.

$wp_ozh_click['0click'] = 'No click'
Default text for zero click

$wp_ozh_click['1click'] = 'One hit'
Default text for one click

$wp_ozh_click['clicks'] = '%% hits'
Default text for several clicks, where %% will be replaced by a number

$wp_ozh_click['method'] = 2
Value can be 1, 2 or 3.
There are 3 ways to modify the link html to add the tracker. Each has advantages and drawbacks, but all validate any Doctype up to XHTML 1.1. If you want things to remain simple, just skip this setting and leave its default value
Depending on the chosen method, <a href="http://site.com"> will become :

  • Method 1:
    <a href="http://site.com" onclick="window.location='/go.php?http://site.com'; return false">
    Cool : status bar shows real link without further trick.
    Less cool : doesnt work with "open link in new window"
  • Method 2:
    <a href="/yourblog/go.php?http://site.com">
    Cool : works with "open in new window" and doesn't require Javascript enabled
    Less cool : shows ugly link "/blog/go.php?http://site.com" in status bar
  • Method 3:
    like method 2 but also modifies status bar to hide the ugly and sometimes annoying "yoursite.com/blog/go.php?" part with onmouseover="javascript:window.status='http://site.com'; return false"
    Cool : status bar shows real link.
    Less cool : adds a few bytes of html
  • I'd suggest you use preferably method 2, or at least method 3. Method 1 is really less accurate since it doesn't keep track of links opened in a new window

$wp_ozh_click['do_posts'] = 1
Value can be 1 or 0 :
Do you want to add a counter to links in your posts ?

$wp_ozh_click['do_comments'] = 1
Value can be 1 or 0 :
Do you want to add a counter to links in your commenters comments ?

Now onto the link title features :

$wp_ozh_click['get_title'] = 0
Value can be 1 or 0.
Get remote page title the first time a user clicks a link to store it along with hits in the table. This will slow down the first clicker, by 1 or 2 seconds maximum, time for your website to retrieve the distant page and parse it.
Note : mostly untested feature. It uses fopen(), check your host has enabled this (if not, the plugin will work anyway, and title will simply be empty)

$wp_ozh_click['get_title_forcerefresh'] = 50
Value is an integer.
Refresh remote page title every XX clicks. Set to 0 if you don't want to use this feature. If you chose to use it, the higher traffic – then clicks – you get, the higher you should set this. Examples : 50 for Joe's blog, 3000 for Slashdottish blog.
To be honest this is really a gadget – almost totally useless :)

$wp_ozh_click['extensions'] = array ( lots of extensions )
Most common non html file extensions. These are files that have no title html tag, so their link title will be the file name (somefile.zip for example)

Then, top link features :

$wp_ozh_click['top_limit'] = 5
Default number of top links to be displayed by wp_ozh_click_topclicks() (see above, Template Tags)

$wp_ozh_click['top_pattern'] = '<li><a href="%%link_url%%" title="%%link_title%%">%%link_title_trim%%</a>: %%link_clicks%%</li>'
Default pattern used to display top links (see above, Template Tags)

$wp_ozh_click['trim'] = 15
Default maximum length of link titles (0 not to trim)

Tips and Tricks

Here are listed a few tips or thoughts I've had during the development and test of the plugin.

» As a file download counter
You can use this plugin as a download counter to see how popular are your files :-P
To do so, you can either specify count="1″ in the download link html tag, or link them with an absolute file (http://site/blog/download/file.zip)

» Use with Matt's Asides
If you are using Matt's asides or something similar, you'll have to modify a bit your index.php
Replace

  1. echo wptexturize($post->post_content)

with

  1. echo wp_ozh_click_modifyhrefs(wptexturize($post->post_content))

» Use with blogrolls
Similarily, if you want to use the feature on a blogroll link list for example, modify the php code to add wp_ozh_click_modifyhrefs().
Remember one thing : each link counter display (in title on in plain text) will cost 1 SQL query. Know what your server can handle before doing such things :)

» Invisible tracker for weak SQL servers
You can use the plugin to track clicks at no SQL cost : set $wp_ozh_click['track_all_links'], $wp_ozh_click['in_title'] and $wp_ozh_click['in_plain'] to zero. It will still modify your link html tags to add the tracker file to them, but it won't display hit counters along with links.
Now, check your link clicks from phpmyadmin directly, or using the template tag wp_ozh_click_topclicks() (1 SQL query)

History

1.0 :

  • Initial release

1.01 :

  • improved : only one query if same url repeated
  • fixed : no javascript in links for rss outputs (so the feed validates)

1.02 :

  • fixed potential SQL injection

Wow

It took me almost longer to write this doc than to write the plugin itself :)

Shorter URL

Want to share or tweet this post? Please use this short URL: http://ozh.in/2a

Metastuff

This entry "Click Counter Plugin For WordPress" was posted on 17/09/2004 at 4:58 pm and is tagged with , , , ,
Watch this discussion : Comments RSS 2.0.

527 Blablas

  1. Ozh says:

    Benjamin » Obviously, if there is no go.php file….

  2. […] Ozh’ Click Counter – ?????? ??? ???????? ????????? ?? ??????? ? ???????? ? ?????????. * […]

  3. […] Click Counter Plugin For WordPress « planetOzh […]

  4. […] Ozh' Click Counter – ?????? ??? ???????? ????????? ?? ??????? ? ???????? ? ?????????. * […]

  5. ynk says:

    le monde est petit :)

    je cherche un click counter, rebondis sur 3 sites, et tombe sur ce blog… dans un autre de mes onglets, il y a FFF :)

  6. r3ck0rd says:

    wow… this plugin helps a lot! Thanks there for making this plugin, Ozh! I may include this in my top plugins list :P

  7. r3ck0rd says:

    Btw, why's this effecting the "Read More »" too?

  8. Marco Luthe says:

    OK, seemed to be the links I tried to provide, so commenting actually seems to work.

    What I meant is:
    Anyone can put a link on their site like
    yourblog.com/go.php?http://anothersite.com

    They will all be forwarded via your site and are therefore masking the origin.

    I do not know if this is a really bad security issue, but I wanted to share.

    Thanks for listening.

  9. AVTO says:

    Thanks for creating this wonderful plugin.

  10. iTwins says:

    Excellent plugin and just what I need!

    Unfortunately, it does not work with Lightview for viewing images. Any workarounds would be very much appreciated

    Thanks in advance

  11. […] Ozh’ Click Counter – ?????? ??? ???????? ????????? ?? ??????? ? ???????? ? ?????????. * […]

  12. […] pageviews are counted by a WordPress Plugin called Clickcounter, which as the name suggest, registers a 'click' everytime someone views a page and […]

  13. iTwins says:

    Hi, I need help!

    I've been trying to figure how this "wp_ozh_click_topclicks()" works in WordPress widget but no luck. Can anyone please lend a hand?

    I am using WordPress 2.6 and Click Counter v1.03

    Thanks

  14. Ozh says:

    iTwins » the plugin is not widgetized as of 1.xx . I working on a version 2.0 though, which will me much faster & lighter on the database, with lots of good things, and it will be widgetized.

  15. iTwins says:

    Much appreciated for the quick response, Ozh.

    Great!! I cannot wait. The SQL polling totally smothered my CPU's (actually CPU resources allocated to me by my host).

    In that case, how about in posts and pages? Also, how does "in plain" works, such in the case of your "I love wordpress (6576 views)"? What are the codes?

    Many thanks in advance!

  16. lynn says:

    Ozh,

    I'm happy to help you test something… as long as the code is not in a widget. (Take a look at my site and you'll see why :^P )

    Gimme a shout. Very excited to see this.

    Best,

    LB

  17. indojepang says:

    hi Oz! is this workin with WPMU? what do i have to do if it doesn't?
    thank's.. i need this workin in MU

  18. Ozh says:

    indojepang » it does work on MU.
    Stay tuned on this plugin, I have to release a much better version 2.0 in the future.

  19. indojepang says:

    whoaaaa it's very fast! thank u Ozh! really appreciate!
    i'll stay tuned! :)

  20. indojepang says:

    on second though Ozh, the future is takin too long for me.. :D

    I just wanna clear something… is Google tracker code interfering your plugin? here's the code example:

    if it does… maybe this can be an addition with version 2.0 to include an option for google tracking code..

    i'm just guessing here :P
    thank u.. very much

  21. Carlisle says:

    The plugin works perfect with WP 2.6 but I have a problem that mentioned once on a comment below. As you know, people started to use custom fields more and more. I even created fully functional real estate blogs, video blogs thanks to custom field. But your plugin works when we post a link in content and doesnt work when we create a link via custom fields. e.g. I put this code on my template "beside the_content" :

    <a href="ID, "link", true); ?>" count="1″>

    "link" gets the url from a custom field. But this way plugin doesnt work.

    I worked a lot but couldnt find a solution. I thought you could find a fix for this. Thanks in advance

  22. Khaled says:

    nice plugin, any way to only let the admin watch this counts. like stats for admin

  23. Jhon says:

    I have install this plugin? they only way to view the stats is from my phpmyadmin? or is there a way to view from wordpress

  24. Travis says:

    Hey Ozh,
    How's version 2.0 of the Click Counter plugin coming along? Any projected release dates before month or year-end?

  25. […] Planetozh – He has developed a great Plug-in that counts the number of clicks for all of the links on your site. […]

  26. Ozh says:

    Travis » No, I can't really schedule any date on this, sorry. Too many things to do at the moment :)

  27. Thanks for this creative plugin Ozh, I'll try this first than I'll be back to give my other comment about this plugin performance on my blog.

  28. Malaiac says:

    error in the regex of wp_ozh_click_parse :

    1. <a href="www" title="title" rel="nofollow">anchor</a>

    does not catch the 'class="class"'

    '[^=]{1,}="[^"]+"/'
    should be
    '/\s+?[^=]{1,}="[^"]+"/'

  29. Malaiac says:

    arf ..
    error in the regex of wp_ozh_click_parse :

    1. <a href="www" title="title" rel="nofollow">anchor</a>

    does not catch the 'class="class"'
    better ?

  30. Dave says:

    Hey Ozh,
    This is a great plugin. I've been using it for a couple of years with no problems until today when someone left me a comment saying that all my links were giving him errors. I tested it out and sure enough :

    Forbidden

    You don't have permission to access /go.php on this server.

    Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

    I've double checked file permissions and stuff like that and everything seems to be in order. I'm currently using WordPress version 2.6.5. Any help would be appreciated.

    Thanks.

  31. Ozh says:

    Dave » unfortunately, I have no idea. Not a WP version conflict for sure. You probably changed something in your config (another plugin?)

  32. Mizsia says:

    nice plugin…and i have a question…
    how can i use this plugin with deliciuos_pp in my theme to count clicks and show it beside the title…
    you know … i want to show my favorits links from delicious and then count the clicks with your plugin…
    is it possible?

  33. aSKer says:

    Salut,
    J'aimerais utiliser ton plugin mais il ne répond pas complètement à ce que je recherche…
    Je souhaiterais compter les hits sur certains liens externes de mon site (en dehors du contenu des posts)… Y a t'il une maniere d'adapter ton plugin de maniere a ce qu'il compte les hits sur tous les liens qui auraient l'attribut count=1, et de retourner le nombre de hits à un autre endroit de la page… (en texte simple) ?
    ( par exemple avec un: echo count:'http://www.unsite.com' )

  34. Ozh says:

    aSKer » Non

  35. Zsolt says:

    You need a new table

    eurgh…
    what is a table?
    eehh, sorry:) is it a php file?

  36. Zsolt says:

    Sorry, it was early in the morning :D

  37. r3ck0rd says:

    Hi there. I've been using this plugin for months, then I switched hosting, and now the go.php (located at /wordpress/go.php, and /go.php). And now the go.php can't be accessed (error 403). I've changed all the permission (all go.php and wordpress dir) to 0755. May someone guide me with hints?

  38. Ozh says:

    r3ck0rd » this issue may have been reported already, probably related to server config. Go through all the comments, you may be lucky…

  39. r3ck0rd says:

    this is what I got: http://planetozh.com/blog/?p=105&cp=39#comment-84748
    I'm not sure, the configurations are all exactly the same anyway.

  40. karistuck says:

    I'm making Blog

    I find good plugin here

    When I Active CLick counter in my blog

    Click Counter can't working.

    I have massege "Uups, not found. Sorry!
    Maybe use our search?" from wordpress

    any help thank you

    have a good time~

    url: http://fontuck.pe.kr/click-counter.font

  41. Ozh says:

    karistuck » this message is not part of my plugin, it's generated by your blog. You probably didn't install things as expected. Please reinstall & read all the docs here. Can't help further.

  42. Dave says:

    r3ck0rd –

    Have you found a solution for this? I'm having this problem too?

    Thanks,
    Dave

  43. Dave says:

    Ozh –

    Is it possible the 403 error is an Apache issue? Are then any Apache requirements for this to work?

    Thanks,
    Dave

  44. Dave says:

    Ozh –

    The 403 error on my domain also gives the following informations:

    Apache/2.2.10 (Unix) mod_ssl/2.2.10 OpenSSL/0.9.8i DAV/2 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Server at nothing.golddave.com Port 80

    I hope this helps.

    – Dave

  45. Ozh says:

    Dave: it doesn't help as I can't help. It's probably some configuration somewhere out of WP, but I don't know.

  46. Dave says:

    Thanks, Ozh. No worries. I'm just trying to work it out and looking for help wherever I can.

  47. Dave says:

    Ozh –

    I finally got the problem resolved. I'm not sure exactly but it looks like the problem was related to mod_security. Once I had go.php whitelisted things went back to normal.

    Thanks for the great plugin!

    – Dave

  48. Dave says:

    I have a plugin installed that puts specific links after a post. These links do not redirect to go.php. I'm OK with that but I'm curious how a plugin could write links that don't get caught by this plugin. (It could come in handy for a plugin I'm writing.

    – Dave

  49. Ozh says:

    Dave: it's probably that the plugin is triggered rather late. Edit my plugin and look for the following, at the end:

    1. // Add per-post filtering:
    2. if ($wp_ozh_click['do_posts'])
    3.     add_filter('the_content', 'wp_ozh_click_modifyhrefs', 10);
    4. if ($wp_ozh_click['do_comments'])
    5.     add_filter('comment_text', 'wp_ozh_click_modifyhrefs', 10);

    Replace the two 10 with 999 and it should be fine.

  50. Saeid says:

    Hi there

    I have install and use this great plugin, but I have a question : "Can we disable countering on an specific link on a post ? "
    I look forward to hearing from you soon.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar and sign for a free account
Spam: Various spam plugins may be activated. I'll put pins in a Voodoo doll if you spam me.

Read more ?