Jan 08, 2017

A Better Way to Add Google Custom Search to Wordpress/PHP Site

It is common to use Google Custom Search for Wordpress Site because of its speed, search algorithm, trustability, security, no need of server resources and database load for indexing..etc. This post will explain how to add Google Custom Search in your Wordpress or PHP site without any plugin.

Get CSE Code:

Login Google Custom Search and add a new search engine.

Left side, select your search engine and click on "Look and feel" option

Google Custom Search Engine

Select "Result Only" layout and click "Save and Get Code".Copy it, the code will be like below:


<script>
  (function() {
    var cx = 'partner-pub-xxxxxxxxxxxxxxxx:xxxxxx-xxxx';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
<gcse:searchresults-only></gcse:searchresults-only>

Why Results Only:

I selected "Result Only" layout means not selected to use Custom Search Box because:

1. Google Custom Search box loads background image as watermark. We can remove it with CSS or javascript tweaks but it is against the terms of service.

2. If we use it then need to add javascript code which will be on all pages (because search box will be present in all pages). Google PageSpeed throws following error:

Eliminate render-blocking JavaScript and CSS in above-the-fold content

http://www.google.com/cse/api/branding.css

It affects PageSpeed score and page load time for all pages.

Search Results:

On Wordpress or PHP website, create a page (say https://techbrij.com/search-result) and paste the CSE code where you want to show search results.

Setup Search Box:

As we are using result only from Google CSE script, we will add our own textbox for searching. Put following code in header or sidebar where you want to display search box:


<div class="searchbox">
<form action="https://techbrij.com/search-result" id="cse-search-box" method="get">
  <div>
<?php if (isset($_GET['q'])) { ?>
    <input type="text" name="q" size="35" id="txtGoogleSearch" placeholder="Search Here" value='<?php echo $_GET['q']  ?>' />  
<?php } else {?>
   <input type="text" name="q" size="35" id="txtGoogleSearch" placeholder="Search Here" />  
<?php } ?>
  </div>
</form>
</div>

You can easily set look and feel and customize it as your choice. That's it. Now search it and test it.

Google Custom Search Engine

How It Works:

You can enter keyword to search and on enter, the url becomes

https://techbrij.com/search-result?q={search keyword}

Google CSE script fetches search keyword from querystring and displays search results.

Conclusion:

In this post, we added Google custom search to Wordpress/PHP site considering Google PageSpeed and site performance.

Enjoy Google Custom Search !!