Custom Google Search API Setup Tutorial

googlesearchapi

So today I did a little tutorial on how to setup Google Search API for your blog/website. This could be used instead of the standard search facilities usually provided in WordPress Themes. It’s really easy to setup! You can customise the search to show results only from your blog/website and other searches such as images, video, news and others (see below for full list).

Live Demo
Download Source

How to do it

  1. Get your Google API Key
  2. Put your key in the code below
  3. Customise the search (add your own domain name!)
  4. Customise the styles to suit your website
  5. Enjoy!

The JavaScript

google.load("search", "1", {"language" : "en"});

// Call this function when the page has been loaded
function initialize() {
var searchControl = new google.search.SearchControl();

// site restricted web search
var siteSearch = new google.search.WebSearch();
siteSearch.setUserDefinedLabel("jquery4u.com");
siteSearch.setUserDefinedClassSuffix("siteSearch");
siteSearch.setSiteRestriction("jquery4u.com");
searchControl.addSearcher(siteSearch);
   
//Search API Topics
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.NewsSearch());
searchControl.addSearcher(new google.search.BlogSearch());
searchControl.addSearcher(new google.search.ImageSearch());
searchControl.addSearcher(new google.search.BookSearch());
searchControl.addSearcher(new google.search.VideoSearch());
//others
//searchControl.addSearcher(new google.search.LocalSearch());
//searchControl.addSearcher(new google.search.PatentSearch());
   
// create a drawOptions object
var drawOptions = new google.search.DrawOptions();
// tell the searcher to draw itself in tabbed mode
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
searchControl.draw(document.getElementById("searchcontrol"), drawOptions);
}
google.setOnLoadCallback(initialize);

The HTML

<p>Type in a search below!</p>
<div id="searchcontrol"></div>

The CSS

/* the width of the controls (keep same as gsc-results for flush look) */
#searchcontrol { width:600px; }
.gsc-control { width:600px; }
/* the width of the search results box; no height value = nice auto look  */
.gsc-results { width:600px; }
/* the width of the search input */
.gsc-input { width:20px; }
/* hide "powered by google" (optional) */
.gsc-branding { display:none; }
/* custom colors */
.gs-title a { color:orange; font-weight:bold; }
#searchcontrol a { color:orange; }

Developers Guide