skip to main | skip to sidebar

Related Posts Widget Powered by GooglePreviously, I proposed a related posts widget for Blogger based on Blogger Data API .
This time will do simple adjustments on 2 Google AJAX Search API controls to work as related posts widgets. which should work on any blog as opposed to the previous method which was limited to Blogspot blogs only.

What is the Google AJAX Search API?

The Google AJAX Search API lets you put Google Search in your web pages with JavaScript. You can embed a simple, dynamic search box and display search results in your own web pages or use the results in innovative, programmatic ways :)

Google AJAX Search API Offers 2 handy search controls:
First take a look on both before we modify them..


Google AJAX Search API: Simple Search BoxSimple Search Box

Integrate Web Search, News Search, and Blog Search into your web site, and easily format the results to fit your site's style. You can also display results from your Google Custom Search Engine.

Google AJAX Search API: Blog BarBlog Bar
Put a dynamic Google Blog bar on your web pages. Just enter the searches you want to power the blog bar, and the AJAX Search API does the rest. We support two different form factors — a thin horizontal strip and a wider vertical bar — so it's easy to incorporate dynamic blog content into the layout of your site.

Adjustments:
  1. I will extract tags of current post from anchor (A) elements with the attribute [ rel=tag ] , and use them to execute a blog search.
  2. Will also check that the current page is a post page by matching to a URL pattern.
  3. Using CSS: will hide the search form of the Simple Search Box, also the Paging links and Posts snippets, then will attach the "powered by Google" branding to the widget bottom.
Advantages using Google AJAX Search API over Blogger Data API
  1. Very generic; You are not limited to blogspot blogs, You can use this on other blogging software such as Wordpress, And if you like you can show related posts from other blogs as well.
  2. Blogger Data API didn't support to search by all tags onetime. I had to aggregate each tag feed and calculate posts relevancy. This time we can query all search results once by ORing all tags.
The Adjusted Simple Search Box
<!-- CSS Part -->
<style type="text/css">
   /* bold the section header */
   .gsc-title { font-weight : bold; }
   /* Hide Search box. You can leave the search box shown to check that Tags were extracted correctly */
   form.gsc-search-box { display:none; }
   /* Hide and the paging box */
   div.gsc-cursor-box { display:none; }
   /* Hide result sinppet! */
   .gs-snippet { display:none; }
   /* Hide result url if you are restricting it to your blog */
   .gs-visibleUrl {display:none; }
</style>

<!-- Javascript Part -->
<script src="http://www.google.com/uds/jsapi?key=YOUR-KEY" type="text/javascript"></script>
<script type="text/javascript">

//<![CDATA[

// Load Search API Js v1
google.load('search', '1');

function DummyClipSearchResult(result) {}
function OnLoad() {
   if(!isPost()) return; // If not a post page
   var tags = getTags();
   if(tags.length==0) return; // If no tags found

   // Create a search control
   var searchControl = new google.search.SearchControl();
   // attaches the "powered by Google" branding into that element
   google.search.Search.getBranding(document.getElementById('branding'));

   // site restricted blog search
   var blogSearch = new google.search.BlogSearch();
   blogSearch.setUserDefinedLabel('Related Posts');
   blogSearch.setSiteRestriction('http://www.moretechtips.net');

   // Results are displayed as fully as possible within the object
   var options = new google.search.SearcherOptions();
   options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
   searchControl.addSearcher(blogSearch,options);

   // tell the searcher to draw itself and tell it where to attach
   searchControl.draw(document.getElementById('searchcontrol'));

   // execute search on tags list by logically ORing
   searchControl.execute(tags.join(' | '));
}

// extract tags from A elements that has attribute rel=tag
function getTags() {
   var tags = [];
   var a = document.getElementsByTagName('a'); // get all A elements
   for(var i=0; i<a.length; i++) {
      var rel = a[i].getAttribute('rel'); // check rel='tag'
      if (!rel || !a[i].firstChild) continue;
      var tag = a[i].firstChild.data;
      if (!tag) continue;
      tag= tag.replace(/\n/g,'').replace(/^\s\s*/,'').replace(/\s\s*$/,''); //some cleaning
    if (rel.toLowerCase()=='tag' && tag) tags[tags.length] = tag;
   }
   return tags;
}
// This fucntion check if the current page is a post to execlude index & archive pages
// It looks for a blogspot post pattern like '/2009/01/post-title.html'
// If you'r on Wordpress Change line #4 to: if(!p.match(/^\/\d{4}\/\d{2}\/\d{2}\/[\w\-\_]+\//)) return false;
function isPost() {
   // fixed array of posts you might wanna execulde like 'contact' post
   var x = ['/2009/01/contact.html'];
   var p = location.pathname;
   if(!p.match(/^\/\d{4}\/\d{2}\/[\w\-\_]+\.html/)) return false;
   for(var i=0; i<=x.length; i++) if(p==x[i]) return false;
   return true;
}
// setup on load call back
google.setOnLoadCallback(OnLoad, true);
//]]>
</script>

<!-- HTML Part : where widget is attached-->
<div id="searchcontrol"></div>
<div id="branding"></div>


The Adjusted Blog Bar
<!--
// The Following div element will end up holding the actual blogbar.
// You can place this anywhere on your page.
-->
<div id="blogBar-bar">
<span style="color:#676767;font-size:11px;margin:10px;padding:4px;">Loading...</span>
</div>

<!-- Ajax Search Api and Stylesheet
// Note: If you are already using the AJAX Search API, then do not include it or its stylesheet again
-->

<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&source=uds-blbw&key=YOUR-KEY" type="text/javascript"></script>

<style type="text/css">
@import url("http://www.google.com/uds/css/gsearch.css");
</style>

<!-- Blog Bar Code and Stylesheet -->
<script src="http://www.google.com/uds/solutions/blogbar/gsblogbar.js?mode=new" type="text/javascript"></script>
<style type="text/css">
@import url("http://www.google.com/uds/solutions/blogbar/gsblogbar.css");

/* Customize the title [Related Posts] */
.horizontal_gsblb .titleBox_gsblb {
   display:block;
   float:left;
   font-size:100%;
   padding:4px 4px 0 0;
}
/* Hide the Tags list; You can undo this to check that Tags were extracted correctly */
.horizontal_gsblb div.statusBox_gsblb{ display:none; }
</style>

<script type="text/javascript">
function LoadBlogBar() {
   if(!isPost()) return; // If not a post page
   var tags = getTags();
   if(tags.length==0) return; // If no tags found

   var blogBar;
   var options = {
      largeResultSet : false,
      title : 'Related Posts',
      horizontal : true,
      orderBy : GSearch.ORDER_BY_DATE,
      // restrict by you site
      siteRestriction : 'http://www.moretechtips.net',
      autoExecuteList : {
         executeList : [tags.join(' | ')] // execute search on tags list by logically ORing
      }
   }
   blogBar = new GSblogBar(document.getElementById('blogBar-bar'), options);
}

// extract tags from A elements that has attribute rel=tag
function getTags() {
   var tags = [];
   var a = document.getElementsByTagName('a'); // get all A elements
   for(var i=0; i<a.length; i++) {
      var rel = a[i].getAttribute('rel'); // check rel='tag'
      if (!rel || !a[i].firstChild) continue;
      var tag = a[i].firstChild.data;
      if (!tag) continue;
      tag= tag.replace(/\n/g,'').replace(/^\s\s*/,'').replace(/\s\s*$/,''); //some cleaning
      if (rel.toLowerCase()=='tag' && tag) tags[tags.length] = tag;
   }
   return tags;
}
// This fucntion check if the current page is a post to execlude index & archive pages
// It looks for a blogspot post pattern like '/2009/01/post-title.html'
// If you'r on Wordpress Change line #4 to: if(!p.match(/^\/\d{4}\/\d{2}\/\d{2}\/[\w\-\_]+\//)) return false;
function isPost() {
   // fixed array of posts you might wanna execulde like 'contact' post
   var x = ['/2009/01/contact.html'];
   var p = location.pathname;
   if(!p.match(/^\/\d{4}\/\d{2}\/[\w\-\_]+\.html/)) return false;
   for(var i=0; i<=x.length; i++) if(p==x[i]) return false;
   return true;
}

// arrange for this function to be called during body.onload
GSearch.setOnLoadCallback(LoadBlogBar);

</script>


To implement this on your blog:
  1. Make sure that your blog exists in Google Blog Search like My Blog, Note that you can see results from your blog only.
    If you are not there then you are doing something wrong in your blog!
  2. Sign-up for an AJAX Search API Key for your website You must have a Google Account to obtain a Google API key, and your API key is tied directly to your Google Account. You can generate multiple API keys for your account if you have multiple web sites.
  3. Replace my key with yours where you see [key=YOUR-KEY... ] at the included Js file of the Google API Loader JS.

Of course you can have the controls display related posts from any blog by removing the site restriction.
Or you can set it to "dzone.com" to get fresh related links from everywhere.

AJAX Search API also offers search results as JSON if you wish to use it with a language other than JavaScript..

Update
When I actually tried to use the blog bar on my site, I didn't like all these JavaScript/CSS files that I've to include.
And since I already use jQuery -and who doesn't- I decided to Rebuild the Google blog bar from scratch.

16 comments

  1. news // June 9, 2009 at 4:21:00 PM GMT+10  

    great! thanks .... :]

  2. Mike // June 10, 2009 at 2:08:00 AM GMT+10  

    @Petr Buben,
    you welcome..

  3. Talib // August 13, 2009 at 9:56:00 AM GMT+10  

    Hi Mike,
    thnx so much for your useful tips,
    i wanna use this tuto but as im a beginner i didnt know if i need to implement both of them,(The Adjusted Blog Bar & The Adjusted search box) and where exactly on my blogger template?
    thnx

  4. Mike // August 13, 2009 at 11:01:00 AM GMT+10  

    @Talib,
    You welcome..
    You should only need one of them.. first check how they look like on Simple Search Box or Blog Bar and pick the one you like..

    You will need to go "Layout>Page elements" and add new "HTML/Javascript" gadget. then paste the code inside the gadget content..

  5. gtricks // September 15, 2009 at 5:19:00 AM GMT+10  

    Thanks a lot of these tricks.

    Can you please tell me, would it be OK to place ".gs-result .gs-visibleUrl { display : none; }" into my style.css instead of placing in top of page?

  6. Mike // September 15, 2009 at 10:38:00 AM GMT+10  

    @gtricks,
    you welcome. Sure you can move CSS to external file.

  7. Anonymous // October 21, 2009 at 10:38:00 PM GMT+11  

    Hi,
    this is great...
    Have you rebuilt the Google Ajax Search Api
    using jquery...
    goreanspank at gmail dot com
    Regards,
    Sharon.

  8. Anonymous // January 2, 2010 at 4:55:00 AM GMT+11  

    Great info, thanks a lot.

  9. buy propecia // March 3, 2010 at 4:01:00 AM GMT+11  

    Hi There! Really cool site . Ok so I'm always searching for this kind of stuff.
    I have this fascination thing. Keep up the good work!

  10. aashish // April 27, 2010 at 8:47:00 AM GMT+10  

    A lot of thanks friend...!!!

  11. speak_english // July 17, 2010 at 10:38:00 PM GMT+10  

    great, but a little bit difficult for me!!

  12. Mike // July 17, 2010 at 11:07:00 PM GMT+10  

    @Speak_english,
    and what about this one
    Related Posts widget for Blogger

  13. Batu.tk // October 1, 2010 at 12:58:00 AM GMT+10  

    Hey,

    Great widget really! But I want to ask you something;

    I want to display some search results on my post page with post title. I tried to use but it didn't work in JS. Is there any way to do that? Thank you very much.

  14. Mike // October 1, 2010 at 7:08:00 AM GMT+10  

    @Batu.tk,
    It would be easier if you can post a sample link or email me..

  15. Batu.tk // October 3, 2010 at 10:16:00 PM GMT+11  

    @Mike,

    There's no sample website. I just want to display search results with Google Ajax Search (google.com/cse) about .
    This tag doesn't work in JS of course. I'm just looking for a solution.

  16. Mike // October 4, 2010 at 8:46:00 PM GMT+11  

    @Batu.tk,
    about what? please email me for better assistance..

Post a Comment

Thank you for taking the time to comment..
* If you have a tech issue with one of my plugins, you may email me on mike[at]moretechtips.net
More Tech Tips! | Technology tips on web development

Mike

Mike MoreWeb developer, jQuery plugin author, social media fan and Technology Blogger.
My favorite topics are: jQuery , Javascript , ASP.Net , Twitter , Google..
<connect with="me"> </connect>

Subscribe by email

Enter your email address:

or via RSS