WP-Mix

A fresh mix of code snippets and tutorials

Display the visitor’s Google search terms

A neat trick in your themes is to display the search terms used by the visitor somewhere on the page. Here’s how to do it for visitor’s arriving at your site after searching in Google.

To display the Google search terms used to arrive at your site, add the following snippet wherever it makes sense in your WordPress theme file(s):

<?php $refer = $_SERVER["HTTP_REFERER"];
if (strpos($refer, "google")) {
	$refer_string = parse_url($refer, PHP_URL_QUERY);
	parse_str($refer_string, $vars);
	$search_terms = $vars['q'];
	echo 'Welcome Google visitor! You searched for the following terms to get here: ';
	echo $search_terms;
}; ?>

For example, you could place this snippet just before the loop in your theme’s single.php file. To test that it works, search for something from your site and click the search result to arrive at your site and see the message. Yay :)

Bonus Trick

Here’s a more simplified version of this trick that simply detects Google visitors and displays them a custom message:

if (strpos($_SERVER[HTTP_REFERER], "google") == true) {
	echo "Hello Google User!";
}

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress