How to Customize Search Engine for WordPress?


WordPress has a inbuilt search engine however, it is not as sophisticated as google search engine (for example WP search does not include comments). To use third party customize search engine, you can insert the following code into the function template file e.g. functions.php

function wp_use_google_search( $wp_query ) {
  $s = '';  
  if (isset($wp_query->query_vars['s'])) {
    $s = trim($wp_query->query_vars['s']);
  }
  if (!$s) {  // empty query returns
    return;
  }
  // get current host
  $host = strtolower($_SERVER['HTTP_HOST']);
  
  // use google 
  $search_engine = 'https://www.google.com/search?q=';
  
  // concatenate the query
  $query = urlencode($s . ' site:' . $host);
  
  // redirect to search engine
  wp_redirect($search_engine . $query);
  
  // end the page
  exit;
}
 
// add customized search handler
add_action('parse_query', 'wp_use_google_search');

Another advantage of using third party advanced search engine for wordpress posts indexing is that it reduces the overload of your server especially if there is a large traffic and your bandwidth is limited. You can also customize the search engine e.g. using google.co.uk instead of google.com if you target UK users only.

You can save the above file in a common path that is accessible by all wordpress blogs if you have multiple blogs hosted on the same server (VPS or dedicated server). Thus, at each functions.php at child theme, you can just simply include:

// Assume we save the above function in file /commom/path/to/wp_search.php
require('/commom/path/to/wp_search.php');

Please note, make sure you don’t forget <?php (at the begining of PHP file) .. and ?> (optional end-of-file tag) when you save the above function in an individual php file.

–EOF (The Ultimate Computing & Technology Blog) —

370 words
Last Post: C# Test Mocking Frameworks
Next Post: Code Analyzer from Visual Studio (Alt + F11)

The Permanent URL is: How to Customize Search Engine for WordPress? (AMP Version)

Leave a Reply