How to: Google Custom Search & WordPress

Want to use Google Custom Search together with WordPress? Here’s how to do that.

You need…

  • A Google Account
  • Knowledge how to create/modify WordPress themes
  • A basic understanding of PHP is also very helpful.

General Considerations

Google Custom Search is similar to a site-specific Google search, much like this:

The advantages of using Google Search:

  • Similar pages are ignored (“In order to show you the most relevant results, we have omitted some entries …”)
  • The translation functions from Google can be used
  • It’s possible to search several websites at once
  • You can puts ads there (if you like)
  • The searches can be very easy analyzed with Google Analytics (if you use that)

But there are also some drawbacks:

  • The layout can be customized but of course only to a certain amount
  • If you add a new post or page it takes some time until it’s included in the Google Search whereas in WordPress search it’s immediately visible
  • The search needs to load external Javascript code from Google, which is not as fast as using WordPress

How does it work?

Of couse you need a Google account, if you have got one, visit Google Custom Search and setup a custom search engine there.

There you set up name, keywords, domain(s) to search, layout customizations etc. for your custom search engine (cse).

As the next step you can choose the hosting type of search: “Search Element”, “iframe” or “Google hosted page”. “Google hosted page” means another window from google.com opens and the results are shown there. “iframe” is what I used: The results are included in a special page on your site. “Search Element” is a new features, here a layer pops up below the search field.

I’ll now show how to include the iframe-search into WordPress.

Integration into WordPress

Note: This assumes you are using your own theme and/or know how to edit WordPress theme files!

Step 1: Choose the URL for the results page

If you use iframe, you have to tell Google where the result will be shown, in my case I simply used /blog/search:

Of course the URL should be inside your blog, preferably a WordPress page.

Step 2: Get the code from Google

After setting up your cse you receive two code snippets from Google, one for the search box – another one for the results page:

Step 2: Setting up a result page

To make things easy, use a WordPress page and call it Search, the permalink has to match the URL you entered in the last step:

..and put the “Search results code” from Google into this page, like this for example:

...
<h2>Google search results</h2>
...
<div id="cse-search-results" style=""></div>
	..more code from google..
	<script type="text/javascript" src="http://www.google.com/afsonline/show_afs_search.js"></script>
...
Step 3: Modify the search form

Edit the WordPress theme file searchform.php and insert the “Search box code” from Google there. So it might look similar to this snippet:

<h2 class="widgettitle">Search my blog</h2>
...
<form action="http://YOURDOMAIN/search" id="cse-search-box" name="cse-search-box">
	..more code from google..
</form>
<script type="text/javascript" src="http://www.google.com/cse/brand?form=cse-search-box&lang=en"></script>
...

Now the search widget shows the Google Search field and already is linked to the google results page.

Step 4: Redirecting the WordPress search

One thing is still to be done – the default WordPress search is still present, you could access it by calling: /search/example.

But to be consistent, we redirect this search also to the Google results page. This is a bit more complicated, so I’ll explain this a bit more detailed:

  • First do a search for example using the Google CSE and copy the URL from the result page
  • Take this URL and move the search term parameter (q=..) to the end and remove the term example:

Your result is of course a little bit different…

Now open your main template file (index.php) and insert this code at the top, replacing the URL (inside the single quotes) by the one you created aboved:

<?php if (is_search()) :
	$result_url = 'http://YOURDOMAIN/search/?cx=partner-pub-12345..11&ie=UTF-8&sa=&siteurl=YOURDOMAIN%2F&q=';
	header('Location:'.$result_url.$s);
	exit;
endif; ?>

Make sure, there are no PHP syntax errors (keep a backup of the previous index.php..)

What’s happening here? The is_search()-function is a Template Tag from WordPress, which returns true if the user searched for something. In this case we redirect the Browser to the Google Results page and insert the search parameter from WordPress ($s) into the URL as if the user had used the searchform.

34 Replies to “How to: Google Custom Search & WordPress”

  1. there has to be an easier way to do this. I’ve done it creating a simple searchresult.php template and copied the search results code on that template and uploaded that template to WordPress, created a page and added to that page the default template with the code and styled it with css. It works.

  2. Hi,

    Instead of redirecting you could just disable the wordpress search:
    Just add this to you’re functions.php
    function fb_filter_query( $query, $error = true ) {

    if ( is_search() ) {
    $query->is_search = false;
    $query->query_vars[s] = false;
    $query->query[s] = false;

    // to error
    if ( $error == true )
    $query->is_404 = true;
    }
    }

    add_action( 'parse_query', 'fb_filter_query' );
    add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

    1. No problem! Just insert a link back to the original post.
      I already thought about writing and/or translating some posts in/to German – but until now I didn’t have the time.

      thx in advance.

  3. I do not understand “One thing is still to be done – the default WordPress search is still present, you could access it by calling: /search/example.” Where do I get example ? is it a file?

    1. “example” is the search keyword.

      I’ll try to explain it in other words: If a user (by any means) opens the URL /search/whatever the search-engine from WordPress is being called (and searches for “whatever”. This is not dramatic, but I wanted to point out how to circumvent this.

  4. Great article! I am just starting out in all this and trying to learn more about it – resources like this article are incredibly helpful.

  5. Geile site. Ist gebookmarked ich komm wieder :-)Es wäre tolldes öfteren solche liebevollen gestalteten page im Web zu finden.

  6. Actually im still getting the problem, ive troubleshooted it and found out that its because – when I hide my search results page – using publish as draft – then i get this error – please could you advise on how to hard code remove the search page created for search results from the main navigation – I don’t want to select Private – else you get the “Private:Search Results” showing

    1. Hi –

      I use a custom theme, which simply doesn’t include the search results page in the navigation. So the most easy way would be to choose a theme which lets you hide pages from the navgiation..

      mario

  7. Great article! I am just starting out in all this and trying to learn more about it – resources like this article are incredibly helpful.

  8. Can I modify the Google custom search code to dwell with my site design ? Will it violate Adsense policies If I touch the custom search code ? I will just be editing CSS parameters of the search button, input field and reduce the length of the input box.

    Please help !

    1. Hi –

      For my personal understanding the length and the button should not be a problem. Especially since the length of the search box can already be customized on the Google CSE site itself.

      According to the Terms of Service (http://www.google.com/cse/docs/tos.html?hl=en) this is relevant for the search box:

      “The Search Box shall conspicuously display a graphic that indicates that the Service is provided by Google. Google’s branding guidelines at http://www.google.com/cse/docs/branding.html provide a set of graphic options available. The graphic shall link to the Google site located at http://www.google.com or such other address as Google may designate from time to time during the Term.”

      Hope that helps – otherwise you can visit the official support forum:
      http://www.google.com/support/forum/p/customsearch?hl=en

  9. Worked great for me. I had this already setup, but I never thought to redirect the existing WordPress search with a function. Thank you for this tip! I’m going to link to this tip on my website.

  10. I tried this out on my wordpress blog – it works for Google chrome as i did all the amendments on Google chrome – but on firefox, opera and ie8 it produces the error code.

    Please help i need this in my wordpress – i guess theres some variables that i need to put ?

        1. Hi –

          First: You have to create a Page in wordpress, preferably on the top level and call it “search”, so that accessing “/blog/search/” in your browser shows this page (and not a 404 like now).

          Second: Then put the code for the Google search result on this page.

          This should help..

      1. Thx – all I did was to add “/” in my search form – as I had followed your instructions to a t – after adding the slash to Google giving it the direct link address its working in all browsers :) Tried in Google Chrome, Opera, Firefox and IE8 – Thanks alot!!

      2. Actually im still getting the problem, ive troubleshooted it and found out that its because – when I hide my search results page – using publish as draft – then i get this error – please could you advise on how to hard code remove the search page created for search results from the main navigation – I don’t want to select Private – else you get the “Private:Search Results” showing

      3. Ok i have just tried to hard code to remove my page “Search” and still no luck

        I used the code

        So i went and installed this plugin “Exclude Pages” and all is well

Leave a Reply

Your email address will not be published. Required fields are marked *