Display Google Custom Search results in WordPress if no posts/results found.

Below code helps you to display Google Custom Search results if no posts/results found in WordPress site.

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

<?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=;$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 raw
search.php
hosted with ❤ by GitHub

Have you any alternative or better solution? Feel free to comment below.

Leave a Reply


Please note: These tutorials are meant to be helpful, but please note that I can not and will not be able to help with any implementations or modifications.

tl;dr If you do not understand it, hire me to do it.