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:

    Saeid » Please read the doc here.

  2. Lorand says:

    Bonjour, merci pour ce plugin. je viens de l'essayer sur mon blog WordPress 2.7 mais j'ai quelques soucis. Il désactive la fonction d'un autre de mes plugin (Target Blank In Posts And Comments) qui permet d'ouvrir dans une nouvelle page le lien cliqué. Est-il possible de faire fonctionner ce plugin uniquement sur les liens de mon choix lorsque je crée mon post ? J'ai bien lu la documentation mais l'anglais technique n'est pas très facile pour moi car je débute dans WordPress. Merci par avance et meilleurs voeux :)

  3. […] muitos downloads (eu espero!) encontrei uma alternativa em um plugin de Ozh. Trata-se do Ozh CLick Counter. De uma forma mais ou menos simples, o plugin adiciona no título, ou no html, a quantidade clicks […]

  4. Beee says:

    Hi,
    nice plugin, but I have a question which I didn't find answered in the last 20 pages of comments.

    Is there a way to position/place the number of clicks somewhere else ?

    I don't want the number of clicks directly after the link (in my case, an image) since i use the

    1. <!--more-->

    tag. I'ld like to display it in the metatags.

  5. Ozh says:

    Beee: out of the box, no.

  6. Beee says:

    i don't mind customising it a bit, but don't know where to start or what to edit exactly.

  7. tip4pc says:

    Hello Ozh!

    Can I ask you something about the post view in your entry, which plugin do you use? Is that WP-Postview?

  8. Ozh says:

    tip4pc » it's a custom plugin I wrote for my custom theme

  9. tip4pc says:

    Thanks for answer me, my blog is using WP-Postview from lesterchan.net, but i think it's show a wrong number, because i use a wordpress.com stats, the number of reading in some of my entry is higher than WP-Postview count, could I have your plugins. Regards.

  10. Ozh says:

    tip4pc: it's not packaged as a plugin, it's mixed up with my theme. Don't want to spend time making a plugin of it.

  11. Beee says:

    i've been trying to hide the output from users (which I've seen somebody do) but I can't achieve it.

    how do i make span class=hitcounter only visible for logged in users ?

  12. Surya says:

    How do the template tags work? I want to have a list of the most clicked links on one page.

    I tried to paste:
    wp_ozh_click_topclicks(10) while editing a post thru the admin panel, but that wont work.

    Am I supposed to add it to a php file? How do I go about adding the php file to a post?
    (Links to guides will be sufficient)

  13. Ozh says:

    Surya » this is a PHP template tag. It's intended to be used in a PHP file, not within a post.

  14. Surya says:

    I'd like to add the top list as a post / side link on the site.

    I think I'll create a copy of page.php / single.php, name it toplinks.php add this code to it, then link it.

    Is there a better alternative?

  15. […] Click here to Download and know more about the Ozh’ Click Counter […]

  16. Surya says:

    How can I use this outside of the "post content"

    I'm editing my theme php file to display external links using meta tags, and I'd like them to have to counter too.

    They are a part of the loop, but the link stays as it is.
    Here's my code:

    1. &lt;a href="ID, 'r_link', true)); ?&gt;"&gt;Click Me!</a>

    r_link contains a normal link, but it doesn't get parsed to a new one.

    What can I do?

  17. Surya says:

    I tried adding count="1″ to the code, but that wont work either.

  18. Ozh says:

    Surya: you don't understand the difference between static stuff (HTML code) and server side stuff (PHP code that is dynamically converted to something before rendering). You're mixing HTML and pseudo PHP.

  19. Ozh says:

    Surya: the plugin parses href only within posts.

  20. Surya says:

    Hmm, seems like I'll have to hack the original code to do this.

    I'll wrwite back once I do it.

  21. CappY says:

    I'm getting error 404 when i click link ?

  22. Martin says:

    I'm using this plugin for two years now, it worked fine all the time. Now I made some major changes in most of the links in my blog. With all the unchanged links it works fine, but all new or changed links, it does only show "no clicks". In the sql-database, it enteres the name of the link and the numbers of clicks; but it doesn't show them on the webpage. I cleared and recreated the table wp_linkclicks; and I reinstalled the plugin, but it's still not working. What am I doing wrong?

  23. Surya says:

    Cappy>>>
    I think you've not put the go.php in your root folder. Take that file from the plugin folder and move it to your public_html or whatever root folder you have.

  24. Surya says:

    Hey, suddenly the links are not redone correctly…
    instead of

    1. <a href="abc" rel="nofollow">clickme</a>

    … they now show as

    1. <a>clickme </a>

    Any ideas whats going wrong?

  25. Ozh says:

    Surya: probably href='xxx' instead of href="xxx"

  26. Kris says:

    I have a link that is stored in a custom field within a post. The link is pulled out on the post page by the template. Is there a way use this counter script on this link? I understand the script is designed for in post links not really links in the template. I saw something about the wp_ozh_click_modifyhrefs tag but I am unsure how to use this or if it is even required for my purposes? If it is could you provide me with a syntax on how it should be used? Thanks

    Also the link is used a couple of times on the page, would the counter update for both of the links regardless of which one has been clicked? Or just the specific link that was actually clicked?

    Thanks

  27. Sebastien says:

    Hi, I've done the installation and the sql to and everything. The thing that I don't understand is how do I get the stats out of it. What I have to do and where.

    tks

    Seby

  28. Dave says:

    I've been using this plugin for a long time now but out of nowehere it stopped working. Links are no longer being redirected through go.php and there are no popups woth the link count when I mouseover links. Any thoughts on what I should check to troubleshoot the problem?

  29. Dave says:

    I also noticed that a couple of my other plugins stopped working. When I re-saved the options for one of them it started to work again. Is there a way to re-save the options for Click Counter?

  30. Ozh, great plugin! Is it possible to have it 'ignore' particular links? Say I want to not have it count (and therefore, NOT prepend the /go.php? to the url) a particular link on one of my posts — is there a way I can say "ignore "?

  31. Ozh says:

    James: yes. Just read the doc here :)

  32. Ozh, I checked over the entire page here twice, and I don't see anyway to just have it ignore one particular link. I see that I could sort of do the opposite by setting "track_all_links" to 0 and then manually set each link I DO want to be tracked, but not a way to otherwise have all links tracked EXCEPT one in particular. Can you point me in the right direction? :)

  33. Ozh says:

    James Rintamaki » <a href="http://site.com/" count="0″>link</a>

  34. ah, yes, that works, thanks! (didn't know that worked even with the track_all_links=1 – though, I suppose I should've just tried, huh!)

  35. Simone says:

    Hi Ozh thanks for your greeeeaaat plugin.
    today i updated to 1.3 but now my plugin for images (auto highslide) wont work.. is possible to grab somewhere your first release? it was working like a charm! best regards
    Simone

  36. Sue says:

    Is there a way to display the number of clicks for a link on a separate page? I have some avatars and I'd like to make it so when you want to download an avatar, you have to click on the avatar and a popup window appears with the downloadable version of the avatar, the title, other info, and the number of times it has been downloaded. Can you reply via email by any chance?

    Thanks!

  37. Ryan says:

    Is this plugin functional with 2.7.1?

    I used to love this plugin, then, it stopped working on a few of my sites (after some updates, maybe theme changes, etc.) and now all of my sites. I've tried deactivating, deleting table, then installing again and creating new table and it still gives me the same problem.

    Every link looks correct in the blog post ….go.php/http://….link.ext but always gives me a page not found error.

    Could you maybe suggest why this plugin no longer works for me?

    Thanks,
    Ryan

  38. Ozh says:

    Ryan » Because you made changes that made it go moo, apparently. Unless otherwise stated, all my plugins work with WP up to version 9.9

  39. abdullah says:

    Any blogger version?
    Thanks

  40. SaranR says:

    Hi,

    Great Plugin,

    How can i use this plugin in Archive page or some other pages in theme folder, I like to use it only in my theme files not in post content

    for example,

    I am using post meta(custom field) tag for getting some url and i m showing in my single page like ID, 'url', true); ?>, how can i show count for this link

  41. SaranR says:

    Hi,

    I don't know how to show number of hits in post

    for example

    I have link as "SaranR in post

    for above code I m getting the result is "SaranR" with link

    I would like to get result like " SaranR (450 hits) "

    and

    I can see the number of hits in view soure as title

    pls help me to do this

  42. saranR says:

    It;s working in only content(post area) not it post meta like custom field,

    how can i make it work for custom field?

    anybody there to help?

  43. Hi, greetings.
    Scuse to make a newnee questions, but my issue is as follows:
    The go.php works and redirects to the linked page. But the pluginn doen't shows the number of clicks.
    Where should be LINK (2 hits) remains LINK
    Nothing further.
    Thank you for your attention

  44. bazza says:

    Avdertency!!! only found with lowcase "href=", not found with "HREF"

  45. Sabrina says:

    I'm putting a bunch of photograph thumbnails on a page. They're linked to the bigger version, and I'm using the Lightbox Plus plugin to make the big photos pop up attractively when a thumbnail is clicked. My goal is to see which thumbnails are most popular. Technically, there is a link involved, so your plugin would display how many times each thumbnail was clicked, right?

  46. Ozh says:

    Sabrina » I don't know this plugin, but probably not since the javascript most likely interrupts the process of following the link.

  47. bachterman says:

    bonjour!

    your plugin is very thorughly documented here, and very well functioning on my blog. :)
    however, i have a question: is there a way that i can create a page which displays my most clicked links? like a stats page.
    i've tried using the php code within the content of the page, but to no avail. the stuff works in my skin template. i guess that's because wp can't "compute" php requests inside it's posts and pages.
    maybe a wrapper should solve my problem?

  48. Cau says:

    Greetings!

    I found Click Counter today and I like it. It's really useful, thank you.
    I will use my links only adding an onmousedown behavior:
    onmousedown="this.href = '[…]/go.php?'+this.href;"
    This method will display the correct url in status bar and will work even to new tabs/windows ;)

  49. Interesting, … however why create a table with a UNIQUE key instead of a Primary key?

  50. Ramon Fincken says:

    I have some tweaks and suggestions for this plugin, if you are interested you have my email !

    1. $wp_ozh_click['parse_internal_links'] = false; // Also rewrite internal links such as links to your own blog (read more links) ? default setting: false, values: 0 or 1, or true / false

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 ?