It's like the Facebook Like Button but +1 better!

It's like the Facebook Like Button but +1 better!

Add the Google +1 Button to your Site   

Added to Code by Richard.stokoe on Monday 18th July 2011

This weekend I have spent some time getting Facebook Comments and the Google '+1' button integrated into this site. I had some awful problems on the way and hopefully this blog will distill some of the horrors I've experienced so that you can virtually copy and paste your way to adding 'Social' to your website.


Adding Google +1

The easier of the two social widgets to add is the Google +1 button.

The basic official documentation is here.

First thing you need to do is to import a JavaScript file from Google by adding the following <script> tag to your web page. Ideally, this should go just before the </body> tag, like on this very site. This means that although the Google +1 buttons take a second or two to show up, the main content isn't affected by the loading of the buttons, which may not even be used. And the content of your site, like this one I hope, is the entire reason for its existence. That is what you should focus on showing first.


<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>


Next you need to add a special tag to your webpage where you want the Google +1 button to appear. This can be as simple as adding the following:



<g:plusone></g:plusone>


Keeping it this simple means Google assumes you mean the +1 is related to "the current document".

Now, "the current document", according to the documentation provided by Google is either the address specified in the 'canonical' link in the <head></head> tags:


<link rel="canonical" href="http://richstokoe.com/blog/?id=12">


Or if this isn't available then Google will use the value it retrieves from the document location:


var currentlocation = document.location.href;


If you want to make the button link to another document (for example, if you look at the blogs list on this site, you can see the +1 button for each blog in the list, and not for the current page) you can simply add a 'href' attribute to the special plusone tag:


<g:plusone href="http://richstokoe.com/blog/?id=12"></g:plusone>


For advanced users, there are other attributes you can add and there's a JavaScript API you can hook into as well. The full developer documentation is available here.

Next in this miniseries focussing on how to Socialise your website is how to add Facebook Comments.

Comments...