December 9th, 2011

Add Facebook Like Button in Your Google Custom Search Results

If you are using Google custom search engine for your website and want to add Facebook like button in every search result. See following steps to implement this. Assuming you are familiar with basic HTML ,CSS and Javascript.


facebook like google search result

1. Add jQuery in your page (if not added) in HTML head tag.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

2. Add XFBML (if not added) in HTML head tag.

 <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>

3. login to Google CSE and get code of your custom search engine.

In your code you will see customSearchControl object.

 
   var customSearchControl = new google.search.CustomSearchControl(...);

Add following code after this:

customSearchControl.setSearchCompleteCallback(this, showMyCustomHTML);

4. Add following script in your page

<script type="text/javascript"> 
var showMyCustomHTML =function (sc, searcher){
$.each($(".gs-webResult"),function(i,val){
var url = $(this).find("a.gs-title").prop('href');
$(this).find('.fblike').remove();
AddFacebookLike(url,$(this));
});
if (typeof FB !== 'undefined') {
    FB.XFBML.parse();
}
}
 function AddFacebookLike(url,ctrl){
 ctrl.append('<div class="fblike"><fb:like href="' + url + '" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" /></div>');
}
</script>

Similarly, you can add twitter, Google+, linkedin buttons also.
Hope, you enjoy this. Thanks @labnol.

  • http://www.usefultricks.in UsefulTricks.in

    Good Job…need your help to design a other custom search engine…..

  • Geekworldnews

    Like amazing tutorial thanks for sharing.

  • http://capturedbloggingtips.com/ how to blog

    Excellent job, thanks for live demo

  • Amir

    Hi..
    Am little confused..
    In which page I have to add coded under number 1 ,2 & then at 4..
    Thanks

  • Ravi Prakash

    Can we use this in google search result…

  • Dashen

    Is there an updated version of this tutorial?