How to display Google custom search results in WordPress if no posts or results are found

How to display Google custom search results in WordPress if no posts or results are found

The below code helps you to display Google Custom Search results if no posts/results are found in a WordPress site.

Add this code in the theme's search.php file where you want to display search results from Google.

/* 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
}
?>
View above code on Github Gist