Skip to content

Replace WordPress search with Google using code snippet

Watch tutorial on Youtube.

Use this code snippet to replace default WordPress search with Programmable Search Engine by Google.

Makes WordPress faster and search results more relevant while using Google servers.

Instructions

  1. Create Programmable Search Engine in Google → https://programmablesearchengine.google.com/ and copy “Search Engine ID”.
  2. Create new Page in WordPress. In content paste this shortcode: [veppasearch full="1"] . Use descriptive permalink slug for example find. Do not use word “search” for slug.
  3. Use following code snippet.

Code snippet

  • Replace XXXXXXXXXXXXXXXXX with your “Search Engine ID” from step 1.
  • Replace YOUR-PERMALINK with your permalink slug from step 2.
/* Instructions https://veppa.com/search-code/ */
/* get ID from here https://programmablesearchengine.google.com/ */
global $_veppasearch_id, $_veppasearch_slug;
$_veppasearch_id = 'XXXXXXXXXXXXXXXXX';
$_veppasearch_slug = 'YOUR-PERMALINK';

/**
 * [veppasearch] only search form
 * [veppasearch full="1"] search form and results
 */
function veppasearch_shortcode( $atts ) {
	global $_veppasearch_id;

	$a = shortcode_atts( array(
		'full' => 0,
		'placeholder' => false
	), $atts );

	$q = (!empty($_GET['q'])) ? trim($_GET['q']) : '';

	$wp_version = get_bloginfo( 'version' ); // 5.2
	if (version_compare($wp_version, '5.2') >= 0) {
		// $args added in wp 5.2
		$search_box = get_search_form(array('echo'=>false));  
	} else {
		$search_box = get_search_form(false);
	}

	if(!empty($a['placeholder'])){
		$arr_search = array(
			'placeholder="' => 'placeholder="'.esc_attr($a['placeholder']).'" placeholder-old="'
		);

		$search_box = str_replace(array_keys($arr_search), array_values($arr_search), $search_box);
	}

	$search_results = '<script>setTimeout(function(){
					var s=document.createElement("script");
					s.type="text/javascript";
					s.async="async";                     
					s.src="https://cse.google.com/cse.js?cx='.$_veppasearch_id.'";
					document.getElementsByTagName("head")[0].appendChild(s);                  
					},500);
					</script>'
		.'<div class="gcse-searchresults-only"></div>';

	return $search_box . ($a['full'] ? $search_results : '');
}
add_shortcode( 'veppasearch', 'veppasearch_shortcode' );

/* fix default search form to use google search. update name and action. */
add_filter('get_search_form', 'veppasearch_get_search_form',10,2);
function veppasearch_get_search_form($form, $args) {
	global $_veppasearch_slug;   

	$arr_search = array(
		'action="'.esc_url( home_url( '/' ) ).'"' => 'action="'.esc_url(home_url('/'.$_veppasearch_slug.'/')).'"',
		'name="s"' => 'name="q"',        
		'value=""' => 'value="'.get_search_query().'"',
	);  

	do_action('qm/debug', 'veppasearch_get_search_form');

	return str_replace(array_keys($arr_search), array_values($arr_search), $form);
}

add_filter('get_search_query', 'veppasearch_get_search_query',10,1);
function veppasearch_get_search_query($query) {
	static $q;
	if(!isset($q)){
		$q = (!empty($_GET['q'])) ? trim($_GET['q']) : $query;    
		do_action('qm/debug', 'veppasearch_get_search_query:q=' . $q);   
	}
	return $q;
}


add_action('init', 'veppasearch_redirect_default_search', 1);
function veppasearch_redirect_default_search(){
	global $_veppasearch_slug;
	// redirect to custom search page 
	$s = empty( $_GET['s']) ? '' : trim($_GET['s']);

	do_action('qm/debug', 'veppasearch_redirect_default_search:s='.$s.':is_admin='.is_admin());

	if ( !empty( $s ) && !is_admin()) {
		$location = '/'.$_veppasearch_slug.'/?q=' . $s;
		wp_redirect( esc_url(home_url( $location )) , 302 );
		exit;
	}
}

add_action( 'pre_get_posts', 'veppasearch_redirect_default_search2' );
function veppasearch_redirect_default_search2( $query ) {
	global $_veppasearch_slug;
	if ( ! is_admin() && $query->is_main_query() && $query->is_search ) {
		$s = get_search_query();
		$location = '/'.$_veppasearch_slug.'/?q=' . $s;
		wp_redirect( esc_url(home_url( $location )) , 302 );
		exit;
	}
}

Benefits

  • Fast for blogs with too many pages.
  • Fast for websites with too many daily searches.
  • Better and more relevant search results.
  • Saves computing resources of your WordPress website. Indexing and searching handled by Google.

Drawbacks

  • Google Ads will be shown in free version. You can disable it with paid API.
  • Most of your content needs to be indexed in order to be searched.
  • Search results page will not match your theme.

FAQ

Why not to use word “search” for search page in step 2?

Because “search” slug used by WordPress for default search feature. If you use the same slug then infinite redirect error will happen.

Will this Programmable Search Engine show ads?

Yes, it is free service powered by ads. Google will show ads, even if you don’t use your own Adsense. You can disable ads by purchasing google API.

How to revert back to default WordPress search?

Disable or delete this code snippet to revert back to default WordPress search.

Will this slow down my website?

No, it will speed up search pages.

Will it find all pages on my website?

It will search only pages that are indexed by google. Any private posts or pages hidden behind user login are not indexed.

Will it show latest posts?

Search results depend on google index. If google indexes your new pages in couple minutes then it will show.

Can I see search statistics?

Yes, you can view search statistics on Google’s Programmable Search Engine website.

What is next:

Leave a Reply

Your email address will not be published. Required fields are marked *