Search code examples
phpjavascriptwordpresssearchgoogle-search

Google Site Search - Completely Custom Search Input


I want to use a completely customized search input with Google Site Search. I want to enter text, hit the search button and be taken to a results page. I have this working on my site however I cannot fully control the search input. Initially I wanted to wrap it in a tag like so:

<span class="trigger-a-search" title="Search">Search</span>
<p class="basic-search" id="headerSearch">
    <!-- Search field in here -->
</p>

However, Google provides a block of code to render the form and trying to stick it inside those p tags does not work. The form gets rendered like:

<span class="trigger-a-search" title="Search">Search</span>
<p class="basic-search" id="headerSearch">
    <!-- Google provided code goes here -->
</p>
<!-- Appears here -->

So I cannot control the appearance of the search input box by wrapping it in the tag I need it to be inside.

So I can get a search input on the page and it works, forwarding to the search results page, but I cannot use my own, completely custom, search input that will go to that same specific search results page when you click "Search". How would you do this?


Solution

  • in the search page you don't need to any controls that google provided. you can simply use text box and button. on button click event generate the search string and pass it to the search result page. in the result page you can use google search api to get the search result.

    function initializeGSearch() {
       ws = new google.search.WebSearch();
       ws.setNoHtmlGeneration(); 
       ws.setSiteRestriction('YOUR SITE');
       ws.setResultSetSize(google.search.Search.LARGE_RESULTSET); //8 results
       ws.setSearchCompleteCallback(this, gotResults);
       ws.execute("SEARCH TEARM");  
    }
    
    function gotResults(){
            var resultcontent = '';
            var resultdiv = document.getElementById('searchresults');           
    
            for (i=0; i<ws.results.length; i++)
            {
                var result = ws.results[i];
                var url = result.unescapedUrl;
                var target = getTarget(url);
                var img = getImage(url);
                resultcontent += "<div class='dgsearchresultsbody'><a class='title' href='"+url+"' "+ target +">"+img+""+result.title+"</a><br/>"+result.content+"<br/><span class='url'>"+url+"</span></div><br/><br/>";
            }
            resultdiv.innerHTML = resultcontent;
            addPaginationLinks();
    
    }