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. andy says:

    is there anyway to run javascript in wordpress?

  2. Ozh says:

    andy » ? obviously. You can embed javascript in any web page.

  3. […] Finalmente y viendo este post en microsiervos en el que se menciona este nuestro blog (alexmoreno.net) he decidido eliminar el plugin Click Counter a raíz de este problema. El porqué incluir un plugin contador de clicks me resultaba muy útil para comprobar qué enlaces les resulta más interesantes a mis visitantes, aunque limitaba mucho mi salida hacia el exterior puesto que mis enlaces hacia los trackbacks de otras web como microsiervos no se ven, y una web que no se ve es una web que no existe. La otra opción es la de estudiar que se puede hacer para tener estadísticas y trackbacks… pero el tiempo es oro y de momento no soy rico . […]

  4. Raven says:

    Merci beaucoup! :-) The plugin works fine, exactly what I've been looking for!
    And since you spent a lot of time for the doc, thanks for that too. ;-) After trying douzens of WP plugins without or with bad documentation I appreciate that.

  5. […] Click Counter Plugin For WordPress « planetOzh Click Counter Plugin For WordPress « planetOzh (tags: wordpress plugin plugins blog wp lazysheep) […]

  6. […] Click Counter – Counts the number of clicks on links used in blog posts. […]

  7. […] Click Counter – one of the best. Keep track of how popular links are […]

  8. Nuclei says:

    I like it

  9. I think that there's a SQL injection problem… The go.php script passes the url to the wp_ozh_click_increment() function, which then uses $url directly in a query without performing any validation on it.

  10. […] There is an updated version — 1.02 — of the popularish Click Counter Plugin available. This is a security upgrade, fixing potential SQL injection exploits. Get the full scoop and download links on the author's blog. Technorati Tags: plugins wordpress wordpress plugins   […]

  11. Ozh says:

    Dougal » thanks for the head up. Fixed hopefully now.

  12. […] کمتر آدم فرانسوی رو دیده ام Ú©Ù‡ وقتی ازش انتقاد Ù…ÛŒ کنم یا به کارش ایراد Ù…ÛŒ گیرم در برابرم جبهه بگیره. خیلی هاشون منطقی فکر Ù…ÛŒ کنند Ùˆ یا حداقل با تندی جواب نمی دن. به Ú©Ù…Ú© ) Dougalخدا خیرش بده) این باگ رو پیدا کردیم ولی هنوز قبول نمی کنه Ú©Ù‡ کارش ایراد داره! در هر صورت اگر از این پلاگین استفاده Ù…ÛŒ کنید حتما نسخه جدید رو Ú©Ù‡ این باگ در اون رفع شده، از اینجا دریافت کنید. Ùˆ الا با من طرفید :) […]

  13. Dave says:

    How do I put the download count on the page like you did with the WordPress links?

  14. After further investigation, I think I was wrong about Click Counter being vulnerable to SQL injection.

    It appears that WordPress applies escaping to the $_SERVER['QUERY_STRING'] variable before Click Counter accesses it.

    Sorry about the false alarm.

  15. dirkhaim says:

    About the note in #36 about viewing only as admin: what do you mean by 'the two lines of add filter'? What exactly should we add?

    Is there an options to see this sometimes built in? maybe just commented?

    Great plugin. Thanks.

  16. […] can follow any responses to this entry through the RSS 2.0 feed. You can also leave a response, or trackback from your own site. function openSpellChecker() { // get the textarea we're going to checkvar txt = document.getElementById('comment'); // give the spellChecker object a reference to our textarea // pass any number of text objects as arguments to the constructor: var speller = new spellChecker( txt,"http://jei.afraid.org/wordpress" ); // kick it off speller.openChecker(); } […]

  17. […] حمله انتحاری علیه دیتابیس بطور اتفاقی داشتم دنبال یک پلاگین به اسم Click Counter میگشتم Ú©Ù‡ از اینجا سردرآوردم Ùˆ همین طور مطالب صفحه رو تا پایین Ù…ÛŒ خوندم Ùˆ تا رسیدم به آخر های صفحه ØŒ Ú©Ù‡ یهو دیدم یکی میون اون همه کامنت انگلیسی یه نظر به فارسی نوشته ( نظر شماره (Û±Û¶Û´. دیدم pingback مطلب همین حاج مرتضی الوانی خودمونه Ú©Ù‡ در قسمت نظرات اون سایت درج شده. دیدم یک چیزایی راجه به Ù‡Ú© Ùˆ SQL نوشته است. نگران شدم گفتم حتماً یک خبرایی شده. لینک مطلب رو تا وبلاگ الوانی دنبال کردم. بله درست بود . وبلاگ الوانی یک کوچولو Ø­Ú© شده بوده. اون هم از طریق SQL injection Ú©Ù‡ یکی از برو بچ روسی به داش مجتبی ضد حال زده بود ! البته خیالتان راحت باشد وردپرس امن Ùˆ امان است مشکل از پلاگین کلیک کانتر بوده Ú©Ù‡ توسط مرتضی الوانی Ùˆ Douga کشف شده Ùˆ به اطلاع ozh کسی Ú©Ù‡ پلاگین رو درست کرده نیز رسیده . اون هم رفع عیب کرده است. […]

  18. eric says:

    i just downloaded and installed the click counter on my wordpress 2.0.1 blog. i came across a problem where the click counter wasnt displaying the # of hits as it was suppose to.

    the problem was the visual editor (wysiwyg thing). i had to disable that because using the html mode in there doesnt save the count="inline" code.

    thank you.

  19. Viper007Bond says:

    Haha, WTF, my go.php used 13.5 gigs of bandwidth (with just 300 hits) last month according to Webalizer. XD

    Is Webalizer on crack or is someone doing weird hammerings on the script?

  20. Ozh says:

    Vip » hmm, strange indeed. If this goes on, I would hack a bit go.php to get some logging into a flat file (logging stuff like client, referrers and query string)

  21. Viper007Bond says:

    Alrighty.

    Now, for another question for this great plugin: I currently have it set to display the click count as the title. Can I change that to a plain text count on a link by link basis?

  22. Scott says:

    Should add into go.php to allow only certain referers to use the redirect.

    Also I don't see how I can add link counts for each blog entry in WP — is there something I'm not getting? I want to count how many times a entry has been read.

  23. Scott says:

    I added the code below to my go.php to stop outside hotlinking using go.php

    Also does minor check to make sure the url is correct.

    This will stop those outside referers from stealing your bandwidth and faking refer tags.


    $CHECK_URL = TRUE;
    $CHECK_URL_REGEX = "/^(http:|ftp:\/\/).*(\.+).*/i";

    $CHECK_REFERER = TRUE;
    $ALLOWED_REFERER = "blog.borgnet.us";

    $QS = $_SERVER["QUERY_STRING"];

    //now check if $QS looks like a URL

    if($CHECK_URL && !preg_match($CHECK_URL_REGEX, $QS)){
    //this didn't match
    echo "

    The URL direction does not seem to point to a valid URL.

    ";
    exit;
    }

    if($CHECK_REFERER){
    if (!stristr($_SERVER["HTTP_REFERER"], $ALLOWED_REFERER)){
    echo "

    404 - FORBIDDEN

    Outside hot linking is not allowed.

    ";
    exit;
    }
    }

  24. […] One thing I noticed when I was over there today, is this thing called the Click Counter Plugin. It looks like it's a plugin that will count clicks for all of your links. Very cool idea. […]

  25. Ozh says:

    Vip » just read the doc here

    Scott » checking referrers is a bad idea. Some browsers block referrers by user's choice, or they send no referrer when link is opened in a new window or tab.
    Also, "outside hotlinking" can be useful. For example, download links to my plugins over at wp-plugins.net are not direct links, but go.php?theplugin, so I can actually keep track of all downloads, including those made from wp-plugins.net

  26. Scott says:

    Then all you do is add what referers yo want to allow.

    Its a good idea to use this to stop these spammers in emails. Alot of them use these open redirect url's to scam people.

    If you don't think its a good idea then so be it but I'm sure viper will find out that most of his 13 gigs was from such a thing.

    Now as far as adding counts like you have in the blogroll/links I am still confused how its done and what file to even edit for this.

    Also how do I add the "Viewed 39507 times" in my blog titles?

  27. Ozh says:

    Scott » the view counter is… a view counter plugin. Nothing related to the click counter.
    As for spammers using the redirect, I have not seen one yet, and I've been obviously using the plugin for quite long now. And to be honest I just don't see what the point for a spammer would be to use it.

  28. Iwan says:

    I have the same problem with eric (# 170)

    I already downloaded and installed the click counter on my wordpress 2.0.1 blog. I came across a problem where the click counter wasnt displaying the # of hits as it was suppose to.

    the problem was the visual editor (wysiwyg thing). i had to disable that because using the html mode in there doesnt save the count=”inline” code.

    Ozh, can u solve this problem for us? Thanks b4.

  29. Ozh says:

    To people complaining about the WYSIWYG editor : my feelings are something like "the problem is the editor, not the plugin", and "this editor is a cumbersome piece of crap I won't even look into". Sorry to disappoint, I won't fix anything regarding this issue :)

  30. Scott says:

    Where is this view counter plugin located at? Have you got a URL for it?

  31. Scott says:

    Yes I know there are a few out there but non are like what you have.

    Would you be enclined to email your plug to me?

  32. Ozh says:

    Scott » It's not a plugin, it's bits of code spread in various parts of my theme

  33. Scott says:

    Too bad — you should make a plugin — the ones i have tried either dont work or install instructions are bad or not there.

  34. TN Chick says:

    I love this plugin. Been using it problem free for a long while…. first on Wp 1.5 then 2.0 now 2.1 :) Thanks.

    I had a question today. I called the top links function on my sidebar and have them displayed.

    I was wondering why one of the links said "25 hits" when called with wp_ozh_click_topclicks() however in the actual post/blog entry where I have the link it only shows 2 hits?

    Understand what I'm asking? Just curious…. as I took notice of it today.

    :) Happy Hump Day!

  35. Ozh says:

    TN Chick » might be for example someone clicking on the link, then hitting several times "F5" if the page didn't come fast enough. Or might be hits from crawling bots. Or might be that your view counter plugin doesnt count page reloads. Or might be a lot of things :)

  36. […] Click Counter1.01 […]

  37. Eric says:

    Is it possible to use this plugin not only in posts but perhaps on the sidebar as well?

  38. Ozh says:

    Eric » without hacking (yourself) the plugin, no.

  39. […] Click Counter Plugin […]

  40. Karl says:

    How do I get count to show up at bottom of postings? What code do I use? You could be way more clear on that part.

  41. Ozh says:

    Karl » I don't see how I can be clearer with something you ask, that I don't understand, and that doesn't even seem to have anything to do with this plugin.

  42. Marcus says:

    Lame question: How do i show the most clicked on sidebar? =)

  43. Hamilla says:

    hi there,
    sorry to bother but i have a probl with the click counter on my blog.
    i have changed theme in wordpress, from Desert_Theme (by evil bert) to Equix (by marco sader).
    I used the plugin with a trick to count how many times every single post was reloaded (to have a clue about how many people read it).
    i put the number right before the "trackback", before "comments".
    i have copied everything (i also upgraded to wp2).
    if i switch to Desert Theme i can see the number of clicks right beside to "trackback" but if i switch to equix, even if i copied all the entries into the index.php, i cannot see anything.

    I cannot understand what i am doing wrong.

    any help would be greatly appreciated, thank you in any case!

  44. Ozh says:

    Hamilla » I don't think I can help with anything. You have a problem of plugin modification + theme modification. I don't know what "trick" you used with my plugin, and I don't know the theme you are talking about. I suggest that you simply use a stat plugin instead of using the click counter for something it's not intented to :)

  45. PurpleRain says:

    How to make the click open a new window so that my visitor no need to push back button?

  46. degra says:

    Hi! I've downloaded and installed your plugin. I followed your instructions, but the plugin don't work. I've checked the database table and it's empty, and the links (I've choosed to show the counter only on some links, with count="1″) don't show anything.
    I haven't hack the plugin, since I don't know PHP well.
    The links are on a "page" of my wordpress blog, not actually in the loop of the blog. Can be this the problem? Or what else?
    Thanks!

  47. ioannis says:

    Hi! nice plugin

    Since i am web related programming illiterate, i would like to have some assistance in modifying go.php so that it is able to handle the link index as well as the link itself.

    I want to use it for file downloading and i prefer to give an index number instead of the direct link, therefore the file download will always be tracked…

    thanks a lot

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 ?