9 February 2012

Add a Facebook "like" and Google "+1" button to Magento and integrate them with Google Analytics

Let's start with adding the Facebook like button. On this page: https://developers.facebook.com/docs/reference/plugins/like/, you can create the button as you would like it to appear on your site. When you press "Get Code", you'll get 2 pieces of code.

First we have to add the JavaScript code. To do this, open your head.phtml page, which can be found here:
app/design/frontend/<your template>/<theme>/template/page/html/head.phtml

In this file, add the script, like so:

<script type="text/javascript">
  (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/nl_NL/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

After that, you can add the other part of the Facebook code in any of your pages, where you would like to have the button. If you want to have it in a CMS page, you can create a Custom Variable, by opening the admin part of your Magento shop and navigating to System -> Custom Variables. In there, create a new variable and insert the code in the Variable HTML Value.