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 :
- CREATE TABLE `wp_linkclicks` (
- `link_id` INT NOT NULL AUTO_INCREMENT ,
- `link_url` TEXT NOT NULL ,
- `link_clicks` INT NOT NULL ,
- `link_date` DATETIME NOT NULL ,
- `link_title` TEXT NOT NULL ,
- UNIQUE (
- `link_id`
- )
- );
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
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 :
- <a href="http://www.link.com/page.php">link</a>
becomes
- <a href="yourblog/go.php?http://www.link.com/page.php"
- 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 :
- <li>
- <a href="%%link_url%%" title="%%link_title%%">%%link_title_trim%%</a>: %%link_clicks%%
- </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 :
- <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
- echo wptexturize($post->post_content)
with
- 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


[…] ing that I have been longing for! Ever since the link from this post kind of disappeared. Click Counter for WordPress Plugin Will let you know you […]
[…] unter Hack/Plugin
Filed under: Plugins Cool tools — Carthik @ 1:14 pm
The Click Counter Plugin counts the number of clicks vis […]
So Usefull !
Tanx ;)
[…] Ë¤âÆ±¤¸¥¯¥ê¥Ã¥¯¿ô¤¬É½¼¨¤µ¤ì¤Þ¤¹¡£ ¤Þ¤º¤Ï¡¢http://planetozh.com/blog//archives/2004/09/17/click-counter-plugin-for-wordpress/" title="¥³¥Á¥é (No click)" onmouseover="javascript:window.sta […]
Is there a way to make it show the clicks on the whole page…not just the posts?? Thanks
well obviously, just change your URLs from http://site.com to /blog/go.php?go=http://site.com
Hi again man
I used it on my service blog ( http://services.corelist.net )
but it seems that doesnt work with .gif or .jpg files !
Tanx again…
Ali ix
You mean :
<a href="link"><img src="image"></a>
?
It does work : view the source of the output HTML, there is a counter. The thing is, some browser cant make up their mind between the img alt tag and the href title one
I've noticed that anchors with internal tags are not handled well. soemthign
This is probably not valid html, but I had a user of my site do each tag this way…
What do you mean "not handled well" ? The script is supposed to remove anchors from URL's, is this the kind of behaviour you didn't expect ?
Je veux essayer ton code sur une autre aplication mais ou est-ce que je me conecte avec la base de donner?
Ca ne sera pas aussi simple.
D'une part il faut que tu ajoutes au début du script les infos relatives à la connexion à la base de données, mais surtout, il faut que tu ré-écrives chaque query SQL qui, dans mon script, utilisent la syntaxe ezSQL adaptée pour WordPress (toutes les $wpdb->quelquechose)
Bref, mon script, fait pour WordPress, n'est pas une bonne base pour l'adapter à autre chose.
I am trying to work with your plugin, I think I messed something up. I am getting the error
Warning: Invalid argument supplied for foreach() in /home/sbrady/public_html/linkmaster/wp-content/plugins/wp_ozh_clickcounter.php on line 313.
Any thoughts on what I did wrong? I thought maybe I didnt create the DB correctly, but it seems to be there and set up fine.
did you create a table named "wp_linkclicks" ? Hard to tell if it's a mysql or plugin problem with few infos. What I can do to help, if you want so, is have a look at your mysql db. Contact me by mail (ozh at planetozh.com)
Is it possible to have this check the links for their status (404 or live)
Is there something that can run through the database (in daily or weekly intervals) and do quick pings to each URL and then if the URL returns a 404 the link is turned red or crossed out?
thanks for a great plug in
You could for example use a simple link checker (this example looks neat) to check the url's gathered in `wp_linkclicks`
Then, it's easy for each 404 to do some $wpdb->query("DELETE FROM wp_linkclicks WHERE link_url = $the_tested_url");
When I use this pluguin, the target="_blank" argument does not work. ¿Can you help me?
Thanks
I've found a problem – when you use the Javascript trick to hide the go.php part your feed will also have the onmouseover code, causing the feed to fail validation. Is there any way of disabling the plugin when a feed is requested?
Hmm, indeed. Well. I'll think a bit about this… Thanks for letting me know
@ New Window : don't see what you mean. When I specify target="_blank" (don't forget the quotes) it works.
@ Donncha : fixed ! Get the newer version :)
Mais c'est qu'Ozh devient de plus en plus doué en PHP :)
Bon boulot, bien que je n'avoue ne pas en avoir l'utilité, ne comptant pas utiliser wordpress.
Ceci dit, ça peut être adaptable :)
Je m'entraine, je m'entraine :)
Click Counter Plugin For WordPress
Ooh, nice! A click counter for WordPress! It comes in two parts – a redirect script and a WordPress plugin. I wasn't sure how well it'd work but it was simple to install – after modifying the sql to record and recognise each blog ID all I had to do w…
Click counter pour WordPress
Les développeurs s'interessent de plus en plus à WordPress qui s'enrichit d'un nouveau plug in baptisé Click Counter qui enregistre le nombre de clics effectués sur votre weblog.
E – Emmense Technologies (Have you heard about their wonderful web hosting services?) F – French Frag Factory – A blog that had a WordPress plugin […]
hello, can i see my country logo
I guess you can :)
auto target="_blank"
Problem: Die Links in WordPress haben kein automatisches target. Daher öffnen sich externe Links in den Artikeln im gleichen Fenster und der Besucher kann nicht weiter meinen tollen Blog genießen. Das wollen wir ja nun nicht (no) Lösung: Ich muss…
hey!
any idea how i could implement this plugin selectively — just one one particular page?
i'd like to try this out just on a linklog page (using this plugin: http://rebelpixel.com/projects/wp-recent-links/) but not use it on the index page, etc.
also i am using a different clickcounter for my sidebar links so i don't need it there.
Doug: should be easy. I'm not using wp-recent-links (and it seems a bit too heavy when I just look at the .zip (doh, 14 files for one plugin ?:))
You need to find where the code produces the link, and modify it as follows :
where the code produces something like $link = "<a href=$url>url<a>", you can try adding right after a line like $link = wp_ozh_click_modifyhrefs($link)
thanks — i'll check it out. i guess i didn't realize that each link to be click-counted had to be manually tagged.
well not manual in the wp-recent-links example (just once in the template) but otherwise.
Nice plugin thanx
Ozh, is it possible for you to make it so only users above or at a certain security level can see the hits (either inline or title)? Other peeps wouldn't see the hits nor anything out of the ordinary.
thanks for this plugin. and _blank questions is
wp-admin/quicktags.js file open
and replace
355 line
edButtons[i].tagStart = '<a href="' + URL + '" target="_blank">';
then works link open the new window
Brad » that's easy
At the end of my plugin, enclose the two add_filter triggers between a test on $user_level. For example, if you want only you the blog admin to see hits :
if ( $user_level > 9) {
the two lines of add_filter
}
Didn't test it but it should work
Hi, i have a strange Problem with this Plugin.
At my first install everything goes fine, the counter count the hits.
I had disable the counter temporaily, switch back to enable ->no count. ???
no redirect (http://url.de/go.php?http://blabla.de,
just http://blabla.de. without ?go.php
Whats wrong?
Salut OZH,
Grand merci pour ce plugin! Je l'ai installé hier sans problème, j'apprécie sa simplicité d'installation et la facilité de configuration.
Cependant, j'ai quelquechose qui semble ne pas fonctionner comme prévu et j'espère que tu pourras m'aider. J'ai choisi la method 3 :
$wp_ozh_click['method'] = 3 ;
Mais pourtant, rien ne s'affiche dans la barre d'état lorsqu'on passe la souris sur un lien.
Voilà , c'est très dommage car j'aime vraiment ce plugin et j'aurais bien envie de le laissé installé! Aurais-tu une idée pour résoudre ce problème?
Merci et encore bravo!
(Hi OZH, thanks for your plugin, which is very efficient and simple to install/configure.
I've got a little problem, though. Even if i've chosen option 3 ($wp_ozh_click['method'] = 3 ;), the status bar shows nothing when you mouse over a link…
Maybe you could help me with this?
thanks again.
Ca c'est une question d'adéquation de browser et de javascript, pas de plugin… Je peux rien faire pour toi :)
Tu veux dire qu'avec Firefox 1.O, c'est normal que ton plugin n'affiche rien en barre d'état, même avec cette méthode "3" activée ?
Missi » don't know, you obviously did something more than just disabled then enabled, since it worked first.
Incipit » surement… Si tu trouves une solution javascriptesque compatible avec FF, n'hesite pas :)
ojich scriptov, som narazil na jeden celkom slušný plugin […]
ile to be downloaded. And managed to come across […]
I found the Problem: clickcounter dont work with myMooMus.
I'm getting a headers already sent error on line 549 ish (cant remember) Whats going on?
you screwed something up when editing the script. Check there is no blank line at the beginning or at the end. Or re-get the script.
cheers
didn't copy the last closing php tag properly
stupid mistake
[…] « Geek Tattoo click counter […]
Does this plugin work with WP1.5?
I'm running 1.5 here