Back to Top

Get incoming Search Keywords to your Website/Blog

Previous Post:

Get incoming Search Keywords to your Website/Blog

Nowadays, with the help of professional tools like Google Analytics, you can easily track all the keywords that bring visitors to your WordPress blog. However, you will need more than that to actually benefit from those keywords.

Using a simple PHP snippet you can easily extract all search terms people use to find your website, and then use those terms to display some fancy stuff to them on their landing pages.

Let’s start by firing up your theme’s functions.php file and put in the snippet below:

  1. function bwp_get_search_keywords($url = '')
  2. {
  3.     // Get the referrer
  4.     $referrer = (!empty($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : '';
  5.     $referrer = (!empty($url)) ? $url : $referrer;
  6.     if (empty($referrer))
  7.         return false;
  8.  
  9.     // Parse the referrer URL
  10.     $parsed_url = parse_url($referrer);
  11.     if (empty($parsed_url['host']))
  12.         return false;
  13.     $host = $parsed_url['host'];
  14.     $query_str = (!empty($parsed_url['query'])) ? $parsed_url['query'] : '';
  15.     $query_str = (empty($query_str) && !empty($parsed_url['fragment'])) ? $parsed_url['fragment'] : $query_str;
  16.     if (empty($query_str))
  17.         return false;
  18.  
  19.     // Parse the query string into a query array
  20.     parse_str($query_str, $query);
  21.  
  22.     // Check some major search engines to get the correct query var
  23.     $search_engines = array(
  24.         'q' => 'alltheweb|aol|ask|ask|bing|google',
  25.         'p' => 'yahoo',
  26.         'wd' => 'baidu'
  27.     );
  28.     foreach ($search_engines as $query_var => $se)
  29.     {
  30.         $se = trim($se);
  31.         preg_match('/(' . $se . ')\./', $host, $matches);
  32.         if (!empty($matches[1]) && !empty($query[$query_var]))
  33.             return $query[$query_var];
  34.     }
  35.     return false;
  36. }
function bwp_get_search_keywords($url = '')
{
	// Get the referrer
	$referrer = (!empty($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : '';
	$referrer = (!empty($url)) ? $url : $referrer;
	if (empty($referrer))
		return false;

	// Parse the referrer URL
	$parsed_url = parse_url($referrer);
	if (empty($parsed_url['host']))
		return false;
	$host = $parsed_url['host'];
	$query_str = (!empty($parsed_url['query'])) ? $parsed_url['query'] : '';
	$query_str = (empty($query_str) && !empty($parsed_url['fragment'])) ? $parsed_url['fragment'] : $query_str;
	if (empty($query_str))
		return false;

	// Parse the query string into a query array
	parse_str($query_str, $query);

	// Check some major search engines to get the correct query var
	$search_engines = array(
		'q' => 'alltheweb|aol|ask|ask|bing|google',
		'p' => 'yahoo',
		'wd' => 'baidu'
	);
	foreach ($search_engines as $query_var => $se)
	{
		$se = trim($se);
		preg_match('/(' . $se . ')\./', $host, $matches);
		if (!empty($matches[1]) && !empty($query[$query_var]))
			return $query[$query_var];
	}
	return false;
}

Now in a global theme file (i.e. a file that is included on every page), for example header.php, you might have this:

  1. <div id="content">
  2. <?php
  3.     $keywords = bwp_get_search_keywords();
  4.     // do some fancy stuff here, for example:
  5.     if ($keywords)
  6.         echo sprintf(__('You have searched for %s.'), $keywords);
  7. ?>
<div id="content">
<?php
	$keywords = bwp_get_search_keywords();
	// do some fancy stuff here, for example:
	if ($keywords)
		echo sprintf(__('You have searched for %s.'), $keywords);
?>

To test a specific referrer URL you can pass a $url variable to bwp_get_search_keywords(), for example this:

  1. echo bwp_get_search_keywords('http://www.google.com/search?source=ig&rlz=1G1GGLQ_ENVN265&=&q=wordpress.org&aq=f&aqi=&aql=&oq=');
echo bwp_get_search_keywords('http://www.google.com/search?source=ig&rlz=1G1GGLQ_ENVN265&=&q=wordpress.org&aq=f&aqi=&aql=&oq=');

will give you this:

wordpress.org

By default this function supports a few search engines, but you can add more if you want. For example, to add Yandex (a Russian search engine) you must first check the query var that it uses, which is ‘text’, not ‘p’ or ‘q’ (try searching for something like ‘wordpress’ and you will get this URL: yandex.ru/yandsearch?text=wordpress&lr=10552).

After you have determined the query var, simply append it to the $search_engines array appropriately, like so:

  1. $search_engines = array(
  2.         'q' => 'alltheweb|aol|ask|ask|bing|google',
  3.         'p' => 'yahoo',
  4.         'wd' => 'baidu',
  5.         'text' => 'yandex'
  6. );
$search_engines = array(
		'q' => 'alltheweb|aol|ask|ask|bing|google',
		'p' => 'yahoo',
		'wd' => 'baidu',
		'text' => 'yandex'
);

If there are more than one search engines that use the same query var, split their domain names using the vertical bar ( | ) characters (just like what I have done with the ‘q’ query var).

Notes: If the fancy stuff you are going to do involve the use of WordPress database (for example you get some related posts based on the search terms your visitors use), please remember to escape all the terms to avoid malicious queries.

Print Article Trackback Trackback to this Article   Subscribe to Comments RSS Subscribe to Comments RSS
 Sponsor   Themes by Elegant Themes - $39 for unlimited access to 80+ WordPress Themes!

29 Opinions for Get incoming Search Keywords to your Website/Blog

  1. User's Gravatar
    1
    Jeffrey April 8, 2011 at 3:17 pm – Permalink

    This will be helpful, thank you!

  2. User's Gravatar
    2
    Jeff July 11, 2011 at 11:58 am – Permalink

    Does this work for individual pages?
    I just want to know what keywords are coming in for a particular post so that i could optimize it further

    • User's Gravatar
      3
      OddOneOut July 12, 2011 at 10:34 am – Permalink

      Yes it works for any kind of page, even archive page.

      • User's Gravatar
        4
        Jeff July 14, 2011 at 6:51 pm – Permalink

        After I have installed the codes into my wordpress theme. where can i view the incoming search keywords?

        • User's Gravatar
          5
          OddOneOut July 14, 2011 at 8:26 pm – Permalink

          You can view incoming keywords on any page, of course. Get the keywords right in your theme’s functions.php with this line of code:

          1. $incoming_keywords = bwp_get_search_keywords();
          $incoming_keywords = bwp_get_search_keywords();

          To show them on any page, just add the line below to the corresponding theme file, for example single.php:

          1. echo 'You have searched for ' . $incoming_keywords;
          echo 'You have searched for ' . $incoming_keywords;

          That’s it!

  3. User's Gravatar
    6
    Sandy July 28, 2011 at 8:14 pm – Permalink

    Thanks for a really neat bit of code. I am using it like this, to save the last incoming search term in a custom field:

    1.     $incoming_keywords = bwp_get_search_keywords();
    2.     if ( !empty( $incoming_keywords ) )
    3.     {
    4.                 global $post ;
    5.         update_post_meta( $post->ID, "page_keywords", $incoming_keywords ) ;
    6.     }
    	$incoming_keywords = bwp_get_search_keywords();
    	if ( !empty( $incoming_keywords ) )
    	{
                    global $post ;
    		update_post_meta( $post->ID, "page_keywords", $incoming_keywords ) ;
    	}

    By adding that code to header or footer.php every page will have a custom field “page_keywords” which shows the last incoming search term.to that page/post. When logged in, I then display the information on the page somewhere, like this:

    1.         $meta = "page_keywords" ;
    2.         $keywords = get_post_meta( $post->ID, $meta, true ) ;
    3.         if ( !empty($keywords) )
    4.             echo ' Last Search: "' . $keywords . '"'  ;
    		$meta = "page_keywords" ;
    		$keywords = get_post_meta( $post->ID, $meta, true ) ;
    		if ( !empty($keywords) )
    			echo ' Last Search: "' . $keywords . '"'  ;

    Very useful when logged in and browsing the site.

  4. User's Gravatar
    7
    Mohd Farrukh October 31, 2011 at 2:51 am – Permalink

    Is this script work for custom php script .. ? if not then have u an idea any other script like this for custom php …?

    • User's Gravatar
      8
      OddOneOut October 31, 2011 at 7:39 pm – Permalink

      Of course Mohd :).

  5. User's Gravatar
    9
    SMS January 13, 2012 at 7:38 am – Permalink

    Thank you so much. This will be helpful.

  6. User's Gravatar
    10
    Elvis Shrestha February 4, 2012 at 2:29 pm – Permalink

    Is there any plugin for this? because i am not so good with coding and i might fall into trouble editing my site…

  7. User's Gravatar
    11
    Web Designer February 5, 2012 at 7:06 pm – Permalink

    Many thanks for this, I will be using this code an manipulating to do this on static sites, basically getting keywords and search terms and when a client sends an enquiry can see what the keywords searched for are!

  8. User's Gravatar
    12
    LEPS April 17, 2012 at 12:03 am – Permalink

    i’m using SEO SearchTerms Tagging 2 very helful. But not working with cache plugins.

  9. User's Gravatar
    13
    Karl August 1, 2012 at 10:01 am – Permalink

    Hi! thanks for this code this has been very helpful. I tried it on my site and it works however I think google has stopped working as the referrer does not contain anything on the ‘&q=’ section of teh query string. have you got any work around for this?

  10. User's Gravatar
    14
    sivaguru September 27, 2012 at 11:50 am – Permalink

    Is this code work on core php? or only in wordpress

    • User's Gravatar
      15
      sivaguru September 27, 2012 at 12:17 pm – Permalink

      ok its working thank you..

  11. User's Gravatar
    16
    luminage January 6, 2013 at 1:58 am – Permalink

    I really love your site.. Very nice colors & theme.
    Did you create this site yourself? Please reply back as I’m planning to create my very own website and would love to find out where you got this from or exactly what the theme is called. Thanks!

    • User's Gravatar
      17
      OddOneOut January 7, 2013 at 12:54 am – Permalink

      It’s a custom theme I made for this site :)

  12. User's Gravatar
    18
    Electro Lifes January 9, 2013 at 4:59 pm – Permalink

    Thank you for this helpful article. Very useful for beginners like me.

  13. User's Gravatar
    19
    health February 5, 2013 at 1:53 am – Permalink

    Greetings, I believe your web site could be having web browser compatibility problems.
    When I look at your web site in Safari, it looks
    fine however, if opening in IE, it has some overlapping issues.
    I just wanted to give you a quick heads up! Apart from that,
    great website!

  14. User's Gravatar
    20
    Kia February 8, 2013 at 2:44 am – Permalink

    I can’t for the life of me get this to work. I have followed it to the letter, even testing is fine…

    1. echo bwp_get_search_keywords('hxxp://www.google.com/search?source=ig&rlz=1G1GGLQ_ENVN265&=&q=wordpress.org&aq=f&aqi=&aql=&oq=');
    echo bwp_get_search_keywords('hxxp://www.google.com/search?source=ig&rlz=1G1GGLQ_ENVN265&=&q=wordpress.org&aq=f&aqi=&aql=&oq=');

    …but when I take that out and test it via google.com I get nothing… any pointers?

    • User's Gravatar
      21
      OddOneOut February 11, 2013 at 11:29 pm – Permalink

      Perhaps you should add some echo/print_r function in the function to determine which part is causing trouble (try print_r-ing $query).

  15. User's Gravatar
    22
    Don May 23, 2013 at 4:00 pm – Permalink

    Code isn’t working with Google searches (if you are logged in, as most users are).

    See: http://searchengineland.com/google-change-may-turn-search-traffic-into-referral-traffic-116085

    • User's Gravatar
      23
      Khang Minh May 23, 2013 at 10:20 pm – Permalink

      You are right, time to update this article :)

Speak Up Your Mind!

An asterisk (*) indicates a required field and must be filled.




  • Web page and e-mail addresses turn into links automatically.
  • Wrap codes in: <code lang=""></code> or <pre lang="" extra="">
  • Lines and paragraphs break automatically.

Next Post: