Google Tag Manager: Track Social Interactions

Share Share on Google+24Tweet about this on Twitter9Share on LinkedIn2Share on Facebook4

Google Analytics provides us with a nifty way of tracking social interactions. With a simple plugin, you can track how many +1s and Likes your pages accumulate.

This guide shows you how to activate social interaction tagging with Google Tag Manager and Universal Analytics. The instructions are for Facebook Likes, Google+ +1s (now deprecated since Google Analytics tracks +1s automatically), Twitter Tweets and Pinterest Pins.

Note that if you use a third-party API (e.g. AddThis) these tricks probably won’t work. You’ll need to use the API functions themselves to enable tracking.

Setting up social interaction macros

Well, first of all, you’ll need a bunch of macros to collect the data from your social actions.

So let’s start with Google Tag Manager.

1. Create a new container version
2. Create a new macro of the Data Layer Variable persuasion, and name it Social network
3. Add socialNetwork as the variable name
4. Save the macro

Social Network GTM macro

5. Create a new Data Layer Variable macro, and name it Social action
6. Add socialAction as the variable name
7. Save the macro
8. Create a new Data Layer Variable macro, and name it Social target
9. Add socialTarget as the variable name
10. Save the macro

So now you created three important macros, all making it easier for to track social interactions via Google Tag Manager. Network will pass the name of the social network the action belongs to (e.g. Facebook), Action will pass the name of the action performed (e.g. Like), and Target will pass the name of the page the action occurred on (e.g. http://www.example.com/post1).

Setting up the send tag

For social interaction events to appear in Google Analytics, they need to be sent (d’oh again). To send a social interaction, you need to create a tag which will have the macros we just created as its arguments. This tag is then set to fire upon a social action.

1. Create a new Universal Analytics tag
2. Give it a name (such as Send social)
3. Add your tracking ID (it’s best to store it as a macro)
4. Choose Social as the Track Type
5. Add your macros as the arguments (see image below for clues)
6. Set {{event}} equals socialInt as the firing rule (we’ll come back to this soon)
7. Save tag

Create tag to send social interaction with

Here we create a new tag which houses the arguments the social interaction will have. The firing rule is primed to wait for an event called socialInt, which we’ll send from our social action tags.

Set up Facebook like

Facebook Like Button
I will not go into how to add a Facebook like button to your page, you’ll have to do that yourself. Facebook has a great guide and tool behind this link which will help you create the necessary code.

However, once you have your button in place, you need to somehow track the clicks. This is done by using a callback function. A callback function effectively hijacks the action performed by some HTML event, performs some code, before allowing the event to finish.

Here’s how to create the callback function in GTM.

1. Create a new Custom HTML tag (or use a single tag for all your social share callbacks)
2. Give it a name (e.g. Social Shares)
3. Add the following code:

<script>
if (typeof FB !== 'undefined'){
  FB.Event.subscribe('edge.create',
      function(href) {
          dataLayer.push({
              'event': 'socialInt', 
              'socialNetwork': 'Facebook', 
              'socialAction': 'Like', 
              'socialTarget': href
          });
      }
  );
}
</script>

4. Set to fire after DOM has been loaded ({{event}} equals gtm.dom)
5. Save tag

OK, so here’s your Facebook Like callback function. Upon clicking the Like button, this function is called. Before the Like event is completed, the trigger event for the Send Social tag (socialInt) is pushed into the data layer. After that, the three required arguments are passed along as well. The value for socialTarget uses href, which is one of the parameters of the callback function, and it represents the URL of the page the event occurred on.

By using FB.Event.Subscribe, you can listen to a number of different events (e.g. message send, login). Check the available options in the Facebook dev guide.

Set up Google +1

Google Plus One button

UPDATE: Note that this is pretty much obsolete now, since Google Analytics and Universal Analytics both track +1s automatically.

Again, I’m not going to tell you how to add the button to your page. It’s dead simple, and you can find a good guide here.

With Google+, you need to specify the callback as an argument in the button tag. With Facebook this was automated. Note that there are a number of callback functions you can specify: clicks, interaction starts (when someone hovers or clicks the button) and interaction ends (when someone closes the +1 bubble). I just chose the click since it’s the simplest way to track (though a tad inaccurate).

I chose sendPlus as the callback function name. A sample button code would then be:

<g:plusone href="http://example.com" size="standard"  annotation="none" callback="sendPlus"></g:plusone>

Note that the developers’ reference has the callback as data-callback, but this seems to work as well.

Now to set up the callback function.

1. Create a new Custom HTML tag (or use a single tag for all your social callbacks)
2. Give it a name (e.g. Google Plus One)
3. Add the following code:

<script>
function sendPlus(g) {
    dataLayer.push({
        'event': 'socialInt', 
        'socialNetwork': 'Google', 
        'socialAction': '+1', 
        'socialTarget': g.href
    });
};
</script>

4. Set to fire on all pages ({{url}} matches RegEx .*)
5. Save tag

It’s basically the same as with Facebook.

This callback function hijacks the +1 button click, sends the necessary stuff to the data layer, before letting the +1 event finish.

Set up tweets

Tweet button
To set up a Tweet callback function, you’ll need to make use of web intent events. They add additional JavaScript functionality (such as the option to declare a callback function) to your Tweet button.

Initialize the Twitter widgets with the following code in your HEAD element:

window.twttr = (function (d,s,id) {
  var t, js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
  js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
  return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
}(document, "script", "twitter-wjs"));

You don’t have to make any modifications to your Tweet button code (providing it’s not implemented via a third-party API, such as AddThis.

In your social share Custom HTML tag, add the following code:

if (typeof twttr !== 'undefined') {
  twttr.ready(function (twttr) {
    twttr.events.bind('click', clickEventToAnalytics);  
  });
}
function clickEventToAnalytics() {
dataLayer.push({
              'event': 'socialInt', 
              'socialNetwork': 'Twitter', 
              'socialAction': 'tweet', 
              'socialTarget': window.location.href
          });
}

Here you bind the CLICK event to function clickEventToAnalytics. There are a bunch of different events at your disposal, and you can find them in the developers’ documentation.

Note how I use the global JavaScript variable window.location.href as the target. This is because I didn’t immediately find if any target parameters were available in the callback function.

Set up Pinterest Pin It

Pinterest is a bit problematic, since when you load the pinit.js script, it replaces any code you may have used in the link tags. This is problematic because Pinterest doesn’t provide any callback functions, so the social share push would need to be added directly to the link code. With pinit.js, any modifications you do are erased upon page load.

However, you can get your pins tracked using auto-event tracking. With a Link Click Listener in place, create a Custom HTML Tag with the following content:

<script>
  dataLayer.push({'event': 'socialInt', 'socialNetwork': 'Pinterest', 'socialAction': 'Pin It', 'socialTarget': window.location.href});
</script>

The firing rule for this is:

{{event}} equals gtm.linkClick
{{element classes}} contains pin_it_button

So once the Pin It button is clicked (the link has “pin_it_button” in its long list of class names), this custom HTML tag pushes the event into the data layer, after which your social share event tag is fired.

Test implementation

So now you have your callback functions which provide the data, the macros which store the data, and the Universal Analytics tag which sends the data. Wonderful!

Save your container version and publish it.

Now go to a page on your site where the buttons can be found. Use a debugger like Firebug, or Chrome’s Developer Tools, and load the page. Pay attention to the Network tab in your debugger, and click Like or +1. You should see something happening, namely a GET request to www.google-analytics.com. Check out the headers of this request, and you should see something like this:

Network tab in Chrome

Here you can see the query parameters.

sa is Social Action (Like)
sn is Social Network (Facebook)
st is Social Target (URL of the page)

Of course, don’t forget to check Google Analytics itself (it might take some time for the data to appear).

Social Interactions in Google Analytics reports

Share Share on Google+24Tweet about this on Twitter9Share on LinkedIn2Share on Facebook4

Comments

  1. Mehdi says

    Hi Simon,

    Thanks for the article.

    Question: this technic works with the classical Facebook like template but it doesn’t seem to work for all the facebook like codes. Is it possible?

    It perfectly works works with this code:
    (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = “//connect.facebook.net/en_US/all.js#xfbml=1&appId=255115191817″;
    fjs.parentNode.insertBefore(js, fjs);
    }(document, ‘script’, ‘facebook-jssdk’));

    • says

      Hi Mehdi,

      The FB.Event.subscribe(‘edge.create’) function only works with XFBML (the example in my post) and HTML5 (your example) implementations. Any other method would require custom callback function setup.

      Simo

  2. Olli says

    Thanks for this Simo. Works great.

    I would add “event equals gtm.dom” to the rule and if (typeof FB !== ‘undefined’) {… } around the script to make sure that the FB variable is loaded on the page and the script won’t give you errors if it’s not.

    Olli

    • says

      Thank you, Olli!

      Those are excellent tips and definitely in line with GTM and JavaScript best practices. I did the respective modifications to the code.

      Simo

  3. says

    Thanks for the post –
    I’ve followed this to the t — even gone back and triple-checked… and yet the “Google Tag Assistant” keeps telling me that the “Data layer fields should be quoted.” The info listed there on the “Tag Assistant” under “Parsed data layer” shows the data for “event,” “socialNetwork,” and “socialAction” to all be in quotes — but not the ‘socialTarget,” that just shows a.href.
    Do you have suggestions? Else, I’ll have to remove this ’cause it’s turning that Tag Assistant blue instead of green on my pages. Thanks again -

  4. says

    Hi Keith,

    The official word is that variable names need to be quoted. As you can see from my examples, that is what I’ve done. Variable name quoting is done because if the variable name happens to be a reserved word (i.e. a word that has functionality in the code), the code will break.

    However, Google Tag Assistant seems to complain even if the variable values are unquoted as well. This is counter-intuitive and seems to be an error in Google Tag Assistant. There are thousands of reasons to use functions and reserved words in variable values, which is why forcing them to be quoted would be ridiculous.

    socialTarget value is unquoted because it refers to the property of the element that was clicked, which is passed as a parameter to the function above. If it were quoted, it would pass “href” as a string!

    So even though it might be aesthetically unpleasant, forget the Google Tag Assistant “Suggestion” and enjoy the fact that the code works :)

  5. says

    Hi , I have followed your setup on this page as you described but I am having some problems, I keep getting the data layer error where i need to add quotes. I don’t have a data layer installed, just the tag manager code, using Universal analytics and I am using the CMS Joomla, latest edition. Also for some reason, I keep getting the error in the floodlight, but I have no control over this as it is a part of the adsense network, I think.

    If you could assist me I would be appreciate it very much. y url for the site is http://www.history1700s.com

    Thanks
    Rick

    • says

      Hi Rick,

      Actually, you always have a data layer “installed” when using GTM. You just don’t always use it (even though GTM itself uses it in the background on every page load).

      If you’re following the code I wrote, you’re also using the data layer. See the dataLayer.push() function in the FB code snippet? That’s you pushing stuff into the data layer.

      What you’re probably referring to is Google Tag Assistant’s warning “Data layer fields should be quoted”. This means that when you’re naming data layer variables, they should always be quoted, so that you don’t use reserved words.

      If you look at the code above, all data layer variable names are quoted correctly. I spoke to a Google engineer about this, and the warning is over-sensitive, meaning that according to tag assistant, data layer variable VALUES should be quoted as well. But that’s ridiculous, since if you quote a variable value, you’re casting it as a string. In my example above, I’m using a variable reference as the value, so quoting it would essentially screw things up completely.

      So if tracking social interactions works, forget about Google Tag Assistant’s warning. It’s a bug in the add-on.

  6. Paul Pettengill says

    Great work! I really appreciate the tip about storing the tracking code as a macro, I was getting annoyed finding it each time I wanted to add a GA/UA tag.

    I noticed a small error in Step 4 of Setting Up The Send Tag, it currently reads “4. Choose Social as the Tag Type”, and I believe it should read “4. Choose Social as the Track Type”

  7. A says

    Hi Simo,
    Nice post :)
    I would like to ask if it works also with a Google Analytics tag instead of Universal .
    And if it does, where I can see the result in Google Analytics.

  8. A says

    Hello again,
    I’ ve created a custom html tag for facebook like:

    FB.Event.subscribe(‘edge.create’,
    function(href) {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Facebook’,
    ‘socialAction’: ‘Like’,
    ‘socialTarget’: href
    });
    }
    );

    and I fired it {{event}} equals gtm.dom.

    I’ ve also created a google analytics tag with web my web property-id, enabling display advertiser features clicked and track type, social.

    Social tracking parameters, social network : {{social network}}, social action {{social action}} and target {{social target}} (which are data layer variables macros: social network ->socialAction etc). And I’ve fired the tag {{event}} equals socialInt.

    I’ve checked the tags in preview & debug mode, and they work fine.

    The problem is:
    After 5 days, I compared the likes in google analytics with those in the website and are not the same number (the analytics displays are less). The articles, that I’ ve looked at, were published few days ago. What I am doing wrong? What i should look?

    Thanks,
    Angeliki.

    • says

      Hi Angeliki,

      The Like button displays Likes and Shares on-site along with all Likes and Shares that occur on Facebook. So if your posts are getting attention in Facebook as well, the result will be different in Google Analytics, since it only measures physical clicks of the button.

      As such, you might think it’s a useless feature, but the whole point of measuring plugin interaction is the same as with all on-site measurement: what do people do on your site and what actions do they take. Measuring if people click a button is a nice way of measuring “engagement”, since each click sends an event which, for example, makes the visit a non-bounce visit.

      I hope that made any sense :)

  9. Suhel says

    Hello Simo,

    I have created the code for LinkedIn share button, but not have tested . Can you please check once whether I am doing correctly, thanks in advance.
    Linked Share GTM code:

    function LinkedInShare() {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Linkedin’,
    ‘socialAction’: ‘Share’,
    ‘socialTarget’: elementurl
    });
    };

    Thanks
    Suhel

    • says

      Hi,

      That code is OK, except for the elementurl. You can get the URL of the page by replacing elementurl with window.location.href

      This function will only work if the actual LinkedIn button tag has the attribute data-onsuccess=”LinkedInShare”.

      Simo

  10. says

    Hey Simo, Do you have the code for sending Facebook and Google Shares , and Facebook comments? I also am trying to figure out the trackback part, and I don’t understand it.
    Thanks.

    • says

      Hi,

      I believe that the Facebook Share button has been deprecated in favor of the Like button. When you click “Like”, you’ll have the option of sharing the content to your friends.

      I believe this applies to the +1 button as well, so if you click it, you’ll have a chance to share the content to your circles.

      If you mean “Facebook comments” as in “Like box”, the contents are loaded via an iFrame, so you can’t track clicks that occur within.

      And do you mean trackback = callback? A callback is a function that is called upon a certain trigger. With Facebook Like button, the trigger is a button click. It’s the same as if you’d use an onclick=”function();” argument in your button HTML code.

      • says

        Sorry Simo, I meant the Track Back, in GA, and I figured the Comment may not be able to track it because of the iframe., my like and share buttons are not in iframes though. and i was wondering if they were trackable in a sense, by using a code like you provided for likes.

        On another note, Can you point me to the setup for the GTM for me to see who is visiting and is Not logged in as a user on my sites? If you visit the forum on my site, you will notice that I have visitors that are not logged in, but they do not, show up in the GA, as far as I can tell, they are not actually in the Forum, but elsewhere on the site.
        Also, Is it possible to combine similar tags into 1 tag for tracking? My GTM is so large that I am considering starting over lol, with the basic code, then start over with the auto event tracking, my downloads for example, i have two different tags for downloading PDF and text files. I was wondering if I could combine those tags into one overall tag, without messing up the data in GA.

        Thanks,
        Rick

      • says

        Hi Rick,

        OK, I think I misunderstood what you were trying to achieve :) Anyway, check this developer reference: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe

        There’s a bunch of callback functions for your different Facebook action types. For example, if you want to track “Send” button clicks, you’d create a callback request like:

        FB.Event.subscribe(‘message.send’,
        function(url) {
        dataLayer.push({
        ‘event’: ‘socialInt’,
        ‘socialNetwork’: ‘Facebook’,
        ‘socialAction’: ‘Send’,
        ‘socialTarget’: url
        });
        }
        );

        There’s instructions for tracking comment creation, removing comments, unliking, etc. as well, all in the guide.

        As for the G+ Share, here’s the dev guide: https://developers.google.com/+/web/share/. I’m not sure how to track the Share click, as the guide only gives callback functions for data-onstartinteraction and -onendinteraction, which would refer to the hover actions. Looks like there’s a possible response of “confirm”, which might be used to identify a successful share and on the basis of that you’d send the event to Google Analytics. I’m not going to recommend any other course of action except to Google if people have tried to reach the “Share” button callback somehow.

        For your second question about logged in and not logged in users, I would use custom dimensions (I’m assuming you’re using Universal Analytics by now). Create a new visit-scope custom dimension in Google Analytics Admin, and then when someone logs in, push “Logged in” or something else as the value of this dimension. After that you can segment your reports by only looking at visits where the user was logged in vs. visits when users weren’t logged in, etc. Really useful. Adding custom dimensions is really easy. For example, if you have a page which you are 100 % certain every single logged in user visits (e.g. some page where the user is taken to after logging in), you can modify a pageview tag in GTM for that specific page, and add Custom Dimension “Logged In” as one of the settings of the tag. If you don’t have such a page, you can attach the custom dimension to an event that you send every time someone completes a successful login.

        As for your final question, yes, you can combine all sorts of tags using macros and rules creatively. For example, you can create a macro whose only job is to return the file extension of the clicked link. You can then use this macro as the event category of your download event. This way you’ll have just one tag, but it differentiates between the different filetypes the user might have clicked.

  11. says

    Hi Simo, Thanks for the assistance, I just have a lack of understanding on the coding part.

    This code: FB.Event.subscribe(‘message.send’,
    function(url) {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Facebook’,
    ‘socialAction’: ‘Send’,
    ‘socialTarget’: url
    });
    }
    );
    Does it get inserted into the GTM like you wrote in this article for creating Facebook likes in the GTM? If so, is it easier to create a new tag, or like you said in this reply, could I add it to the Facebook like tag already available. And yes, I do use the UA for the GA, I always have used the universal code. I know, I may have to have the script tags before and after the code.

    Sorry about all the questions, I am a Historian, and a Basic HTML man, and I only have a limited amount of coding experience when it comes to java script and the other advanced coding. (think cut and paste, lol)

    • says

      Hi,

      You can use the same tag, just put this stretch of code either after or before the FB.Event.subscribe(‘edge.create’…) structure.

      The less tags the better, since processing each tag requires some extra computation.

  12. says

    Hi Simo, So I put it like this? see below: Or is it supposed to look different?

    if (typeof FB !== ‘undefined’){
    FB.Event.subscribe(‘edge.create’,
    function(href) {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Facebook’,
    ‘socialAction’: ‘Like’,
    ‘socialTarget’: href
    });
    }
    );
    }
    FB.Event.subscribe(‘message.send’,
    function(url) {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Facebook’,
    ‘socialAction’: ‘Send’,
    ‘socialTarget’: url
    });
    }
    );

    • says

      Just a small change, move the closing } on the line before the second “FB.Event.subscribe…” to the end of the entire structure. You want to keep the second FB.Event.subscribe within the if(typeof FB !== ‘undefined’) {} structure as well.

  13. says

    So it would look like: with the script and no script tags on either end?
    if (typeof FB !== ‘undefined’){
    FB.Event.subscribe(‘edge.create’,
    function(href) {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Facebook’,
    ‘socialAction’: ‘Like’,
    ‘socialTarget’: href
    });
    }
    );
    FB.Event.subscribe(‘message.send’,
    function(url) {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Facebook’,
    ‘socialAction’: ‘Send’,
    ‘socialTarget’: url
    });
    }
    );
    }

    • says

      That looks OK, you’ll just have to test it and see if it works :) If you’ve set up your Facebook Like and Send buttons accordingly, those two functions should push the stuff into the data layer for your Social Interaction tag to take care of them.

      And yes, you’ll need <script> in the beginning and </script> in the end.

  14. says

    I set it up as follows
    script
    if (typeof FB !== ‘undefined’){
    FB.Event.subscribe(‘edge.create’,
    function(href) {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Facebook’,
    ‘socialAction’: ‘Like’,
    ‘socialTarget’: href
    });
    }
    );
    FB.Event.subscribe(‘message.send’,
    function(url) {
    dataLayer.push({
    ‘event’: ‘socialInt’,
    ‘socialNetwork’: ‘Facebook’,
    ‘socialAction’: ‘Send’,
    ‘socialTarget’: url
    });
    }
    );
    }
    noscript
    But the version wouldn’t validate
    What did i do wrong?

  15. says

    Simon, when i did the above, I got this error
    1. JavaScript Compiler Error Facebook like Error at line 13, character 22: Parse error. illegal character.
    2. JavaScript Compiler Error Facebook like Error at line 13, character 23: Parse error. missing ) after argument list.
    3. JavaScript Compiler Error Facebook like Error at line 13, character 35: Parse error. illegal character.
    4. JavaScript Compiler Error Facebook like Error at line 13, character 36: Parse error. syntax error.
    5. JavaScript Compiler Error Facebook like Error at line 14, character 22: Parse error. missing ; before statement.
    6. JavaScript Compiler Error Facebook like Error at line 15, character 19: Parse error. syntax error.
    7. JavaScript Compiler Error Facebook like Error at line 16, character 14: Parse error. illegal character.
    8. JavaScript Compiler Error Facebook like Error at line 16, character 20: Parse error. illegal character.
    9. JavaScript Compiler Error Facebook like Error at line 16, character 20: Parse error. missing } in compound statement.
    10. JavaScript Compiler Error Facebook like Error at line 16, character 21: Parse error. syntax error.
    11. JavaScript Compiler Error Facebook like Error at line 16, character 23: Parse error. illegal character.
    12. JavaScript Compiler Error Facebook like Error at line 16, character 33: Parse error. illegal character.
    Can you assist me on this?
    Thanks

    • says

      Rick, as this is now in the territory of syntax error checking and general JavaScript issues, lets continue this by e-mail. Drop me a line at simo.s.ahava at gmail.com.

  16. David says

    Such a simple and excellent implementation with GTM, thanks Simo. Has anyone had success implementing this for pinterest and twitter?

    • says

      Hi David, thanks! I linked to a couple of posts detailing Twitter and Pinterest tracking a few comments up. Looks pretty straightforward, though if I understood correctly, neither API provides a parameter for the shared URL, so you’ll have to use window.location.href to grab that.

      • David says

        Thanks Simo, yep i looked at the code for both tracking options but wasn’t completely confident with it, i’m not a coder. There’s almost no documentation on tracking these types of Social Interactions with GTM. I’ve replied to Kenneth above to see if he implemented either tracking successfully.

        In your example, to track both FB Likes and G+1′s, using Custom HTML tags. For Tracking tweets, i wonder is it better to use the github code as a Custom JS macro or tweaking it and using it for a Custom HTML tag.

        Hopefully as more people use GTM, there will be more documentation and tutorials available,

      • says

        Hi,

        I updated the post to include Tweet callback as well.

        There’s really no need to use a Custom JS macro, since the idea behind macros is to create reusable helper functions which return a value. With the Tweet callback, it’s basically a one-off call, which populates a bunch of data layer variables. So I would definitely use a Custom HTML to keep the function calls to a minimum.

  17. Luis says

    Hi Simo and congratulations for this amazing post. ( btw i found your blog today and i’m glad i did because the internet lacks good tutorials on the GTM )

    For the last couple of days i’ve been trying to implement social tracking thought events but after many hours i was unsuccessful.
    The reason i need the events it’s because i deal with traffic volume and i want a real time tracker on what’s going on with the posts.

    After reading many websites and google documentation i have tried to use a Link Click Listener ( and using the element id ) to track a custom share button that i have and i can’t get it to work. The problem isn’t on the GTM because if i try the code on the normal post and assign an id to a link it fires the TAG but on the share buttons, likes, tweets, it doesn’t work. It seems like it is something blocking the tags or it can’t reach the element ids on the button links.

    Do you have any thoughts on this?

    Thank you.

    • says

      Hi,

      Thanks for the comments, I do my best :)

      Depending on how the social share button is implemented, a link click listener might not work. For example, adding a Facebook Like button might look like a normal DIV placement on your site template, but in reality the script replaces your DIV with an iFrame, and you can’t track clicks inside iFrames.

      You’ll need to first consult the documentation of the social share button: do they provide a callback function? If they do, you can update the button code to include this callback function (at least Twitter and Facebook provide callbacks).

      If you’re sure there’s not code replacement going on, it might be that what you’re clicking is not actually a link (in HTML terms), but rather a DIV or SPAN or BUTTON or something similar. So you might want to try it with a GTM Click Listener, which listens to *all* elements, not just links.

      Also, if you have a third party sharing toolbar, like AddThis or ShareThis, you’ll have to check their API documentation to see how tracking to GA can be achieved.

      Getting social interaction tracking requires quite a bit of detective work, especially if you’re using a social share plugin created by a third party. Sadly, first party documentation is often very lacking or outdated as well, so there’s a lot of ground to cover.

      If you want, I can take a closer look (we can continue this discussion over e-mail).

  18. says

    hi Simo
    Thanks for the article.
    can you please show me how to add tracking tag to the linkedin share button?
    also, i followed all the steps but on the final step testing the implementation, with the chrome debugger checker, i dont see the code running. can you please check my site to see if I implemented the code properly?
    thanks in advance
    Meitav

    • says

      Hi Meitav,

      I checked your implementation, and at least Facebook Likes are being sent correctly to Google.

      Note that Google tracks +1s automatically, so you don’t need to implement the code I had for them in my post. There seems to be a bug with +1s, where they are sent multiple times (2-3) with each click. This seems to occur in your implementation as well. I left a question about this on the Product Forums, I’m still waiting for an answer.

      As for LinkedIn, you’ll probably need to either use the LinkedIn Share Plugin Generator to create an “official” share button, and add

      data-onsuccess=”shareIn();”

      as an attribute. Then you need something like this in your Custom HTML tag:

      function shareIn() {
      dataLayer.push({
      “event”: “socialinteraction”,
      “socialNetwork”: “LinkedIn”,
      “socialAction”: “Share”,
      “socialValue”: window.location.href
      });
      }

      data-onsuccess is where you link to your callback function, which is run upon clicking the share button.

      Another way to get your LinkedIn clicks tracked (you’ll need to test this), is to have a Link Click Listener running on all pages. Then, in your LinkedIn share tag, you’d add a rule

      {{event}} equals gtm.linkClick
      {{element id}} equals li_ui_li_gen_1393326427733_0-link

      Every time someone clicks the LinkedIn link, your “Send LinkedIn Share” tag will fire, if the rule is as above.

      I know this sounds a bit complicated, but you’re really close to getting it right :) I can’t help with the +1 multi-tracking problem, since that’s something that Google has to repair.

  19. Jonny says

    Hi Simo,

    Thanks for the great post! And I have 2 questions.

    1. Is the method working with Universal Analytics only? Or also works with classic Google Analytics?

    2. How long it takes to display the result in GA?

    Thanks in advance!

    • Jonny says

      Issue solved.

      I was using codes, after switching to , the tracking result displayed accurately in my GA report.

      I think you can highlight this in your article, “The code doesn’t work with FB buttons”.

  20. says

    I’m trying to track facebook, twitter and googleplus logins. I already put this code in the body but no pageViews or custom dimensions tracked in GA

    dataLayer = [];

    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({‘gtm.start’:
    new Date().getTime(),event:’gtm.js’});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!=’dataLayer’?'&l=’+l:”;j.async=true;j.src=
    ‘//www.googletagmanager.com/gtm.js?id=’+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,’script’,'dataLayer’,'GTM-XXXXXX’);

    dataLayer.push({‘socialType’: ‘id; ?>’});

    • says

      Thanks for the help. I got GTM to track Facebook and Twitter logins. For some reason Google+ logins don’t track. I changed the settings of the Google segment to views instead of users and it somehow worked.

    • says

      Just a quick note, this code looks incomplete because WordPress automatically strips source code out of the comment field. So there are no typos in Sonny’s dataLayer.push() function.

      • says

        Thanks Simo. Your suggestion of using gtm.dom instead of the All Pages macro in the firing rule helped a lot. Also you suggested moving the dataLayer above the GTM code and putting the dataLayer code directly instead of pushing it after the GTM insert script fixed the issue.

  21. David says

    Great Simo, i’ve eventually found time to implement this today so will be testing over the next few days.

    In the meantime, when i check “Social Source and Action” with a Secondary dimension “Page title”, the social action figures don’t represent the figures on the actual page Social button.
    For example, a new article published recently shows 1 FB, 3 G+, 1 Pin but the report only shows 1 Pin. I’ve checked other articles and its completely random.

    • says

      Hi David, if the count comes from the service’s own API (as it usually does), the number is the total number of interactions on the post, i.e. all tweets, likes, shares, comments, etc.

      That’s why Social Interactions should be measured in the first place: to identify which social interactions originated from your on-page share buttons.

      • David says

        Thanks Simo, that makes perfect sense. Sometimes something is staring right at you and you miss it.

  22. says

    Hello and thank you for this extremely helpful post!

    I only have one question. In my site i use both addthis and default facebook code. I saw that Universal Analytics tracks both. Is it possible to exclude addthis likes from tracking and keep the default facebook like code?

    Again, thank you!

    • says

      Hi Christopher,

      From what I’ve understood, AddThis manages social clicks and tracking with its own, proprietary solution. So you’ll have to look at AddThis’ tracking settings to turn it off.

      • says

        I didn’t get any social tracking from addthis in Universal Analytics before Tag manager setup. So is there any rule we can apply in Tag manager to exclude addthis tracking?

        Thank you.

  23. says

    Thanks Simo for sharing this guide. I have been searching around the Internet for days and tried loads of ways to do the social tracking, based on what others have advised, but none of them worked. Your instructions are nice and easy to follow and have worked first time :-) Will be keeping an eye out for more of your articles. Thanks, Michael.

Trackbacks

Leave a Reply

Your email address will not be published. Required fields are marked *