Skip to content

Instantly share code, notes, and snippets.

@dipakcg
Created December 1, 2016 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dipakcg/9479153f385c4100e38a04822f2b5d1b to your computer and use it in GitHub Desktop.
Save dipakcg/9479153f385c4100e38a04822f2b5d1b to your computer and use it in GitHub Desktop.
Display Google Custom Search results in WordPress if no posts/results found.
<?php
/* Add this code in theme's search.php file where you want to display search results from Google. */
$query = get_search_query();
$query_new =str_replace(' ','%20',$query);
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=0&rsz=8&q=".$query_new;
$body = file_get_contents($url);
$json = json_decode($body);
for($x=0;$x<count($json->responseData->results);$x++){
?>
<p>
<h2> <a href="<?php echo $json->responseData->results[$x]->url; ?>"><?php echo $json->responseData->results[$x]->title; ?> </a> </h2>
<span> <?php echo $json->responseData->results[$x]->url; ?> </span>
<h4> <?php echo $json->responseData->results[$x]->content; ?> </h4>
</p>
<hr />
<?php
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment