This tutorial outlines two techniques to customise Google’s Custom Search Engine:
- Generating your own custom styled search form
- Fetching the search results on page load rather than the default which requires the Google provided search form to be submitted
This enables you to place your custom styled search form anywhere on your site (for example in a global site header), and when the form is submitted the search results are automatically loaded as soon as the user lands on the search page – as opposed to the default behavior which requires submission of the Google provided search box.
This is a sample global form that I use in my header file, which submits to the url “/search”. I will leave the CSS side to your imagination.
<form id="search" method="get" action="/search"> <fieldset> <input type="text" name="q" value="" placeholder="Search Records" /> <button type="submit">Search</button> </fieldset> </form>
On my search page, the following code displays the Google CSE search box and pre-loads the results which are passed in from PHP’s $_GET. Don’t forget to replace myUniqueID with your Google CSE unique ID.
<!-- div container to display search results -->
<div id="cse" style="width: 100%;">Loading...</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function() {
var customSearchControl = new google.search.CustomSearchControl('**myUniqueID**'); // change this to your unique ID
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF); // open results in current window
customSearchControl.draw('cse'); // set the results div id
customSearchControl.execute("<?php if (isset($_GET['q'])) echo filter_var($_GET['q'], FILTER_SANITIZE_STRING); ?>"); // run the search using the value of $_GET['q']
}, true);
</script>
That’s exactly what I needed… Thank you!
This is what i have been looking for for a long time. Is there any way to control the number of search results displayed?