Tracking Social Media Sharing and Button-Clicks with JavaScript and WordPress

In the past several years, one trend has become apparent on blogs and websites of all sizes: Google Analytics is clearly the preferred way to track everything from a user’s operating system to the popular of links on a website’s homepage. This popular method of tracking and monitoring each visitor who comes across a website might seem to be a bit broad, but users can actually use JavaScript on certain links to track not only the actual clicks that a link gets, but where those clicks come from and in-depth information about each user who clicks it.

This innovation is powered by a combination of JavaScript and the aforementioned Google Analytics, and it supported natively by several social networking buttons and APIs. For this reason, click tracking in Google Analytics is popularly applied to social networking buttons by blogs so that the site administrators can see exactly which content is the most popular, where it is the most popular, and with what kind of user it is the most popular. It’s a marketing and publishing tool that, at the present time, has no near competitor or comparison.

Because it uses two third-party tools (Google Analytics and Javascript/jQuery) this click tracking can actually be brought right into WordPress with minimal effort. All it requires is adding or modifying social networking links which get published right alongside a website’s content. Users will never know the difference, but site administrators will find the difference quite stark. Visitor traffic will now be more effectively monitored, as each reader’s social media habits will be on the record of the website’s Google Analytics account.

Here is how to enable this functionality on any WordPress blog by altering a few links and including a few jQuery scripts:

Step 1: Adding the Social Media Links to a WordPress Page

The first step a developer must take is to add the actual social media links to an entry, or potentially modify the existing links which are already paced alongside website content. These links must be made to interact with the actual API, rather than simply create a “tweet” or “like” link using a standard <a> tag. To do this, each link will look a bit different and will take on characteristics that blur the line between XHTML and native API. Facebook’s link, in particular, is the most offbeat in appearance. Here’s how each link should look, using full WordPress variables and natively interacting with the website in question.


<fb:like href="<?php the_permalink()?>" send="true" showfaces="false" width="100" layout="button_count" action="recommend"/ ></fb:like>


<a href="" data-url="< ?php the_permalink();?>" data-text="< ?php the_title();?>" data-via="your-website" class="twitter-button">Tweet this!</a>


<script type="in/share" data-url="<?php the_permalink();?>" data-counter="right"></script>

Google Plus:

<g:plusone size="medium" callback="plusone_vote"></g:plusone >

It’s evident that many of these buttons make use of XML, and what should be apparent to the keen observer is that the Google Plus and LinkedIn buttons will require JavaScript not only for click tracking, but indeed to interface with the server and pull a user ID which will be used when the site’s readers share information. That’s particularly advanced, and it’s the new way that most social media websites are combining XML, XHTML, and their own APIs in combination with OAuth to enable secure, adaptable sharing. Now it’s time to make the buttons work and track user interactions.

Step 2: Using JavaScript to Make the Buttons Interface with Social Media Sites

Now, the jQuery inclusions must be placed into the site’s <head> tag in order for each of the buttons demonstrated above to be fully operation. This is done on a per-website basis, so only add the JavaScript snippets for the websites that the blog in question will advertise to users.

Facebook is once again the most unique snippet of code, as it combines a <div> tag with its JavaScript excerpt to make things work. That <div> tag can actually be placed anywhere within the template, but, for the sake of organization, administrators would be well-advised to place it in the same area where all of the social media buttons are displayed.
Here’s what Facebook users will need in order to make the “Like” or “Recommend” button work properly.

First, the jQuery must be placed into the <head> tag. The script for Facebook is below:

window.fbAsyncInit = function() {
FB.init({appId: '', status: true, cookie: true, xfbml: true});
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
e.async = true;

After this has been included into the <head> tag, likely within the selected template’s header.php file, a <div> tag must be placed within index.php and any other templates which will show these buttons to the readers. That div tag is:

<div id="fb-root"></div>

Next, the Twitter button must be activated by using jQuery. Unlike the procedure described above for the Facebook button, the relevant code for the Twitter button (or “Tweet this!” link) does not make use of a standalone <div> tag. Instead, it identifies the button code wherever it might be in the template and applies the script’s actions directly. The Twitter script is also much shorter than the Facebook script; it is contained in a <script> tag and placed right below the Facebook variant in the site’s <head> section:

jQuery(document).ready(function($) {
var e = document.createElement('script');
e.type="text/javascript"; e.async = true;
e.src = '';
document.getElementsByTagName('head')[0].appendChild(e); }

The LinkedIn and Google Plus buttons actually use the exact same basic API, and this means they can be combined into just one jQuery instance placed within the site’s <head> tag. This is convenient for developers, as it saves them time, processing power, and space, and it’s relatively simple to do. This script identifies the unique Google Plus tag or, in the case of LinkedIn, the “script” share tags, and converts them into active buttons. When it’s all put together, the code looks like the following example:

jQuery(document).ready(function($) {
var e = document.createElement('script');
e.type="text/javascript"; e.async = true;
e.src = '';
var e = document.createElement('script');
e.type="text/javascript"; e.async = true;
e.src = '';
document.getElementsByTagName('head')[0].appendChild(e); }

Notice that, in these instances as well as the script which activates the Twitter button, the scripts which make the buttons active are actually hosted remotely. This, too, helps to speed the loading process. Also, each button is paired with a script that will only load the button once the website has loaded. All too often, scripts hold up a website by requiring their information be loaded before the page finishes loading itself. This can cause a number of unsightly errors for most readers. A more sophisticated script, like the examples above, helps to prevent this from occurring.

Step 3: Tracking Interaction with the Social Media Buttons

Each of the social media buttons above will display a graphically-rich link that encourages users to share a post via their favorite websites. Paired with each button will be a small counter which shows the number of times a reader has shared the post with each website, and this will also encourage sharing the content off-site at the web’s most popular social destinations. With all of this encouragement, all that’s left to do is add some JavaScript which interfaces with Google Analytics and causes it to pick up information when a user clicks one of the social media buttons.

It all sounds pretty good, but there’s one pretty big drawback. The remote social networking site has to have an API which supports this kind of interaction between their own button and a service like Google Analytics. Luckily, Facebook and Twitter fully support this type of tracking and user engagement. Unfortunately, sites like LinkedIn, Google Plus, StumbleUpon, and many others, simply do not support this kind of tracking. Of course, Facebook and Twitter are leaps and bounds more popular than the latter three sites, so this may well be a non-issue on most blogs.

To track the clicks given to Facebook and Twitter buttons, two new snippets of code must be added to what has already been placed within the <head> tag of the current theme’s “header.php” document. This code actually replaces the entirety of what was added to the document to enable the Facebook button without tracking, so simply paste the information below between the existing <script> tags as they pertain to the Facebook button:

window.fbAsyncInit = function() {
FB.init({appId: '', status: true, cookie: true, xfbml: true});
FB.Event.subscribe("edge.create",function(response) {
if (response.indexOf("") > 0) {
clicky.log(response,'Facebook Like Facebook Page');
} else {
clicky.log(response,'Facebook Like / Share Post'); } });
clicky.log(response,'Facebook Send Post'); }); };

With this information replacing the original Facebook button, everything a user does when they interact with Facebook via the button on the website will report back to Google Analytics using basic jQuery functions. This means site administrators can track the general locations, user agents, browsers, devices, and other information for all of the users who share a site’s content. Let’s do the same thing for Twitter.

Instead of replacing the entire body of jQuery script that was used to enable the Twitter button, the snippet below is simply added to the existing <script> tag in order to turn the button from a standard way to share into a way to share and track those who choose to do so. Here’s what it looks like in production:

var e = document.createElement('script');
e.type="text/javascript"; e.async = true;
e.src = '';
$(e).load(function() {
function tweetIntentToAnalytics(intent_event) {
if (intent_event) {
var label =;
_gaq.push(['_trackEvent', 'twitter_web_intents',
intent_event.type, label]);
clicky.log(document.location.href,'Twitter '+label); } }
function followIntentToAnalytics(intent_event) {
if (intent_event) {
var label = + " (" + + ")";
_gaq.push(['_trackEvent', 'twitter_web_intents',
intent_event.type, label]);
clicky.log(document.location.href,'Twitter '+label); } }'tweet', tweetIntentToAnalytics);'follow', followIntentToAnalytics); });

With the above code added to the existing Twitter <script> tag, the work here is basically done. The header.php and index.php files should be edited, saved, and uploaded, and the code for including the social media buttons via XHTML should be made universal across every page where content is published. When that has been done, the social media buttons will be live and ready to track.

Be sure to do some bug testing, click the buttons when they first appear, and wait 24 hours for the results to appear within the Google Analytics Dashboard. When everything looks right, it’s time to sit back and enjoy the rush of statistic that will be available as users post a site’s content all throughout the web’s most popular social networks.

(36 Posts)

Vladislav Davidzon is the principal of US-based online marketing consultancy Vladislav Davidzon & Associates, developing integrative solutions through high impact search engine optimized WordPress websites for socially responsible customers of all sizes around the world.


  • Nicolas

    Thanks for this article.

  • Tom Sommer

    Would be nice if Google would just implement this directly in ga.js

  • It’s late and I’m probably missing something, but it looks like you have Clicky Analytics code included as well. Before I start trying this out,  Is Clicky required to get this working ?

  • benjieboo

    Really helpful article, especially the tracking the social buttons! :) has google plus or linkedin or pintrest updated their tracking options?