Adding Google search to a FlatPress theme
Original article by Igor Kromin. Many thanks to Tongara for the Smarty4 Fix
Although FlatPress includes a search function, it is possible to replace it with Google search. You may have to tinker a bit with the FlatPress code itself, but the end result is a fully functional search for FlatPress that is supported by the power of Google.
This article will not go into the details of how to create the Custom Search Engine (CSE). Google has a good tutorial on that already. Check it out here. The prerequisite for this post is that you have created and configured the CSE as a results only page.
The first thing to do is create a template file that will display the results page. Below is a sample without any styling. The file name is search.tpl, this is placed along with the rest of the .tpl files in the theme directory. Add the CSE code between the comments. This has to be included between the literal tags since it contains JavaScript.
$ Template file: search.tpl
{include file="header.tpl"} <div>Search Results</div> {literal} <!-- Start CSE code --> ... <!-- End CSS code --> {/literal} {include file="footer.tpl"}
After the template page is created, the index.php file from FlatPress needs to be modified. Below are the modified lines from the file, with the original include call and return statement commented out. The return statement is changed to set the module variable to the name of the template file. This has the effect of rendering the search results page whenever the 'q' URL parameter is specified. Since CSE uses 'q' as the default parameter, this works right out of the box.
$ FlatPress file: index.php
... } elseif (!empty($_GET['q'])) { // include('search.php'); return $module = 'search.tpl'; //search_main(); } else { ...
Now to finish it all off is the search form itself. This can be added anywhere in the existing theme. In my case, I added it to the header.tpl file so that it is rendered as a part of the menu. The code below populates the search form with the previous search parameters and sets the submit action to the FlatPress Blog URL so there is no hard-coding anywhere. As a nice feature, some JavaScript is used to submit the form when the user presses the Enter key.
$ Search Form
<div>Search</div> <form method="get" action="{$flatpress.www}"> <div> <input type="text" name="q" add_hook="echo $_GET['q']" {literal} onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }" {/literal} placeholder="Search" autofocus> <input name="search" type="submit" value="Search"> </div> </form>
That's all there is to it! This small change removes the need to use the default search plugin and gives much better results too. The only downside is that the results take a second or two to render as they are loaded on the client side via JavaScript, so sometimes the search results page looks blank immediately after it is loaded.