Like the blog? Get the book »

Using Google Custom Search in WordPress

Using Google Custom Search in WordPress

Once a WordPress powered site starts getting quite a bit of content, the default built-in search becomes fairly useless. It just isn’t very smart. If you wrote a comprehensive article about He-Man, but since have written five other articles that just mentioned He-Man in passing, a search for “He-Man” will turn up your comprehensive article sixth. There have been various tweaks and plugins and whatnot that attempt to improve upon this default functionality. But why not leverage the best search engine ever written instead?

The Basic Setup

Sign up for the (free) Google Custom Search Engine.

Google Custom Search

The default code that Google gives you is the pure-JavaScript version. It works fine, but it doesn’t allow you to separate the search form and the results. I find that kind of ridiculous, as it’s far more common to want to host the search form on all pages (like in the header or sidebar) and have that take the user to a dedicated results page.

To get the code that is the separate search form and results, go to the Look and Feel section after creating your CSE. Choose the iframe method, then click the “Get Code” button.

Update: apparently the iframe method is no longer available, so hopefully a workaround using existing methods is still possible.

Select the iframe option

Fill out the URL of your search results page (this will be a page you’ll create and publish later). Then take the top bit of code and place it were you want the search form to be. Likely in your sidebar.php file or header.php file, wherever your site design dictates would be good to have a search form.

Choose other options

On this site, we put it in the sidebar, and applied our simple button class to match other buttons on the site. Don’t be afraid to alter the HTML of the provided code as long as it’s simple alterations like adding a class name to an input. Probably best to not meddle with the overall structure.

Google Custom Search at DigWP.com

Now create a page in your WordPress admin called “Search Results”, in the content, paste in the second bit of code. Make sure the slug you give the page matches the URL you gave the CSE for the location of the results page. If they don’t match, you can easily change the <form>‘s action attribute in the HTML.

Specify custom Page URL

You’re all set! Now you can enter search terms on any page of your site, and be taken to a dedicated search results page where the results will be displayed. These results will of course be real Google search results, but limited only to your domain. So that He-Man article? It will almost certainly be on top, because Google’s importance algorithmic will put it there.

Using Multiple CSE’s for Subsections of your Site

On CSS-Tricks, I have a search area that looks like this:

Google Custom Search at CSS-Tricks

Notice the little options beneath the search box which indicate in what area you would like to search. It might seem like this is some fancy custom development, but it’s really not. In reality, it’s just four different Google Custom Search Engines. Only one of them displays at a time though, depending on which search option is active. Here is an example of that looks like:

<div id="search-area">

	<form action="/search-results/" id="search-all" class="header-search-form default-search">
	    ...
	</form>

	<form method="get" action="/" id="search-articles" class="header-search-form">
	    ...
	</form>

	<form action="/forums/index.php" id="search-forums" class="header-search-form">
	    ...
	</form>

	<form action="/snippets/search/" id="search-snippets" class="header-search-form">
	    ...
	</form>

	<div id="search-by">Search: 
		<a href="#search-all" class="cur-search">All</a> 
		<a href="#search-articles">Articles</a> 
		<a href="#search-forums">Forums</a> 
		<a href="#search-snippets">Snippets</a>

		<p id="browse-archives">Or... <a href="/archives/">browse the archives</a></p>
	</div>

</div> <!-- END search-area -->

Notice the class names on the very first <form> includes “default-search”. All these forms are hidden by default, and only that class name reveals it. So while there are four forms here, only one displays. Also note the second form actually submits to “/” and uses the GET method. This is for “articles only” search and uses the default WordPress search.

The other areas (Snippets, Forums, and All) use Google Custom Search Engines. So for those three, I used what is described above in the basic setup. For the Snippets area, I told the CSE to use the domain http://css-tricks.com/snippets/ – so the results that it returns are limited to that subdirectory.

I use a bit of jQuery to allow the search option links to be clickable to change which area is to be searched. When a new option is selected, hide all forms, show the correct corresponding form, flip around classes to indicate the new option is selected. Easy cheesy.

var $searchByLinks = $("#search-by > a");

$searchByLinks.click(function() {
    var $el = $(this)
    $(".header-search-form").hide();
    $($el.attr("href")).show();
    $searchByLinks.removeClass("cur-search");
    $el.addClass("cur-search");
    return false;
});

Then to keep what users type in all search inputs in sync at all times, here is another quick bit:

$(".header-search-input").keyup(function() {
    $(".header-search-input").val($(this).val());
});

Now we’re all set! Users can now search subsections of the site if they choose, and all we had to do was use multiple Google CSE’s. The user likely doesn’t even notice and no custom development was needed.

20 responses

  1. Rather than including search form directly it is more proper to put it in special searchform.php template. That way it is automaticall fetched by get_search_form() function.

    You can also filter get_search_form hook if you are adding search form with plugin.

    • Indeed that’s a good idea. If you don’t wish to ever use the default WordPress search again, replacing the code in searchform.php and using get get_search_form() function is a good way to go.

  2. Hi Chris,

    Whoops, re my previous email, all seems to now be working as I wished.

    i.e. clicked on results now open in the same window. Maybe I was imagining things before!

    Sorry for the ‘false alarm’.

    Regards,

    Ray Atreides

  3. Can you control de ads showing in the result page?

    I was testing it here and it shows Adsense. Lame :(

    Regards

    • There are two ways to handle that. For $100 per year, you can remove the ads. Or, you can connect it to your own AdSense account so you earn the money from the ads served there. Both are pretty reasonable options in my opinion. Thanks for mentioning that.

      • I believe that there was a third option; non-profit organisations can use it without the ads, for 0 bucks. It was probably a year ago when I checked it, but I guess that this third option is still available.

    • Hell, 100$ ^^;

      I guess adding your own AdSense code is the best choice.

      Thanks.

  4. Hi Chris,

    Many thanks for this excellent and detailed article on setting up Google CSE. I have just followed your clear instructions and am almost there. I do have one problem that you may be able to assist me with. When clicking on a result on the new Search Results page Google opens a new window / tab. I do not want it to do this.

    I just require the page to load in the same window / tab as the Search Results page is on. Hope that makes sense? Your Search Results Page on your site does this so it would seem that it is possible. Any help would be appreciated.

    p.s. I have your your Digging Into WordPress Ver 3. Great read and great value!

  5. What a great and well-thought out article. I tried to install Google Search a year or so ago, but I may have to try again now that I have this to go by.

  6. Do you know how much liberty Google gives you with styling the search results?

  7. Hmm. Not sure.
    On this site it only displays articles from october 2010 it seems?

    • I just fixed that, thanks for pointing it out. For some reason it was still picking up weird subdomains from this server, but I was able to remove them from the results without affecting regular results.

      • Wow, that’s a lot better!

        Now I’d like to say: thanks for this post!

        Did you really pay a $ 100 to keep AdSense out?

  8. Chris,

    Great post! I followed your steps on my site and it worked like a charm.

  9. Wonderful post. I have always tried to integrate Google to my sites but was never able to. Thanks to you, this works like a charm.

  10. Off topic… I know screencasts are a pain for you, but I wonder if you’ve thought of having a series that coincides with the DigWP book? I’ve really learned a lot from the videos at css-tricks.com and was watching “The WordPress Loop” screencast tonight. I got a couple of details clarified by it and it gave me this idea. Just a thought…

  11. can you sort them in anyway? filter them down? The search results here from google leave a lot missing. Same goes for Smashing Mag. Plus it’s not pretty at all. It’s kinda ugh…

  12. is there plugin about this ?

  13. I have a problem on my site.. its showing all forms on the same time.. but when I click on a link its ok

  14. is there no way to set the iframe width for a liquid layout in percentages?

Comments are closed for this post. Contact us with any critical information.
© 2009–2024 Digging Into WordPress Powered by WordPress Monzilla Media shapeSpace