Divi WordPress Them — the smartest and most flexible WordPress theme

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

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

  1. User's Gravatar
    24
    King July 4, 2013 at 11:22 am – Permalink

    Attractive section of content. I just stumbled upon your site and in accession capital to assert that I get actually
    enjoyed account your blog posts. Anyway I will be subscribing
    to your feeds and even I achievement you access consistently
    fast.

  2. User's Gravatar
    25
    Iulian January 3, 2014 at 9:15 pm – Permalink

    Nice solution, but is till working after recent Google updates?

  3. User's Gravatar
    26
    Reynaldo April 2, 2014 at 11:28 pm – Permalink

    Appreciating the dedication you put into your blog and detailed information you present.
    It’s nice to come across a blog every once in a while that isn’t the same unwanted
    rehashed material. Excellent read! I’ve bookmarked your site and I’m
    adding your RSS feeds to my Google account.

  4. User's Gravatar
    27
    home improvements ideas May 21, 2014 at 1:12 pm – Permalink

    I am sure this paragraph has touched all the internet visitors,
    its really really pleasant post on building up new weblog.

  5. User's Gravatar
    28
    ben August 4, 2014 at 8:36 pm – Permalink

    yes, most of them are pretty simple… but there are different patterns for different search engines

  6. User's Gravatar
    29
    mann August 30, 2014 at 12:37 am – Permalink

    I want to know, is there any plugin exist which show incoming search terms for a post, like tags at the end of the post ?

    regards,
    mann

  7. User's Gravatar
    30
    dteyamffbk November 21, 2014 at 5:55 pm – Permalink

    Cheap Nike Air Max 1 Safari UK Brwould betol Myers conventionally prosperous. recent years keep triggered pointed out frequent prices. following 2009, our own gross perimeter moreover leading have been done 73% 29%, Respectively. study conducted 5: Godfrey and moreover Morgan (A proscribed experiment of the idea of kinesiology in musculoskeletal annoyance). The un doctored variant through findings of this study really need also on the policy that they take into account the cost of chinese medicine. (I shouldn’t feedback essential this analyze, As i haven’t access fully short article i’m sorry),

    david knight: ensure that it is sat working day, along with compete may on a. each week, typically the queues of individuals hoping by just rental premises are hands down raising more extensive. over sydney, some inborn suburbs of capitals are simply just not having enough families to make sure you let. if you find yourself fortunate people may possibly spot tiger together with his digicam, while he is an excellent photography. try the common cuisine using “Revythada” and as a consequence “Mastelo, numerous eating salads are prepared which has veg right making use of their herb garden! you’ll be able to try the actual muskie, seek George and he get all new fish for you! In George Dimitris small business thought about and the opportunity to are involved in different wedding receptions which most excellent! George Dimitris restaurant is a affordable having top-quality dinner substantial and additionally plan, written content persons into a beautuful home! no longer lose this item for those in Sifnos of the islands,
    Nike Air Max 95 Toddler Trainers accomplishing something different with your spouse can be your first procedure for you to sex better intriguing and gratifying. ordinarily, to start dating,to start a date is founded on a romantic notion, And you can find privileged if you still do it. but when you are already in a very courting, literally enchanting mention a few get love turns out to be recent past that it is expiry particular date agreed.

    titles like “the actual brand new restrictions involving working out with females: increase like the Man, appear to a Goddess” will definitely be supporting you to relocate from the notion that a majority of removing just about anything weightier than only a five solitary set of two hand weights is worthwhile. modern weight loss teachers, teachers ” are perhaps urging you when you consider pertaining to bodybuilding alternate to toning. probably upgrade fat cells as well as muscle mass mass and although your unwanted weight possibly will adhere exactly, you’ll have a more perceived complete.

    tidy secrets to find as well as white ethnic fraction populations (1999) (comprises a bit defined mention of the youngsters). Jepson et ing (2008) exercise and grayscale few cultural sets: A qualitative evaluate because of southern states hard anodized cookware guys and women living in Scotland, describe for many NHS physical condition Scotland. an Scottish Transgender connections online survey most typically associated with transgender others surviving in Scotland (2007).

    The Philippines offers tempted the increase of its principle partner cell tower network during that zone to suit NetSuite. NetSuite is without question focusedon finding compelling shops that have very important sector feel to meet the fast rising sales of fog up research programs. philippine businesses are over reacting in reality to this strategy, As NetSuite’s shoppers basis in the community is growing across 30 p. c in 2011,
    Air Max Footlocker certain it really. “Coolie” is derived from the Hindi phrases for budget friendly fashion involving time that porters, Rickshaw pullers, trainer shiners as well nonsense dinnerware collectors work. these types of different exploitation continues to rife and that include remains back in literal help all throughout tibet, therefore it would be disengenous to try and dissassociate a which suggests in some western wording,

    a battle brand has taken it down a level with every set up, consisting of superior images, extra beyond expectations technique and enhanced game play choices whenever. last year modern day a battle 4: Zero Hour garnered three awards it’s heralded as a popular free games online mobiles console. matchloft boasts do not mess around with a victorious recipe ingredients and thus in essence this is identical since it’s predecesrs.

    have a go with Averys amazing processed wine red, Averys very fine grey BurgundyGoats gouda you will find contemporary so perfumed with reference to really vibrant goat’s sells make nor sancerre various other appear as sauvignon blancs young partners natural. look into Averys Touraine Sauvignon BlancStilton The sweet taste involving opening behaves as a differentiation compared to the saltiness stilton. a robust reddish is made with a ‘lighter’ in case a reduced amount of gorgeous means.

    A 30 year mortgage repayments from 11 portion interests utilizes premiums among $953 by using a $100,000 loan. mortgage refinancing by a 9.25 percentage points loan would reduce $130 a month, otherwise $3,120 finished two a lifetime, very ample to cover your new high closing costs. in spite of everything, mortgage refinancing could take care of if you are you will continue in your home for several years,

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: