Skip to content

Instantly share code, notes, and snippets.

@luk3thomas
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luk3thomas/8690960 to your computer and use it in GitHub Desktop.
Save luk3thomas/8690960 to your computer and use it in GitHub Desktop.
Google Analytics track Facebook social actions

Add this directly after the opening <body> tag

<div id="fb-root"></div>
<script>(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=477427382375494";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

Then we add the like button somewhere below the facebook code we just added

<div class="fb-like" data-href="{facebook-page-url}" data-width="200" data-layout="button_count" data-action="like" data-show-faces="true" data-share="false"></div> 

I assume you are using jQuery. So after jQuery is loaded, subscribe to the Facebook like and unlike events to have the information sent to Google Analytics.

<script>
(function($){

    var track = function(action, url) {
//      _gaq.push(['_trackSocial', 'facebook', action, url]);  // old, legacy style analytics
        ga('send', 'social', 'facebook', action, url);         // new, universal analytics
    };

    $(window).load(function($){
        FB.Event.subscribe( 'edge.create', function(url){
            track('like', url);
        });
        FB.Event.subscribe( 'edge.remove', function(url){
            track('unlike', url);
        });
    });

})(jQuery);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment