I had a need to add some extra content to a WordPress home page for visitors from Google who were searching for something in particular. In past CMS systems, I’d just put some code in the template to check the HTTP_REFERER server parameter and emit my custom message directly, but this site was using WP-Cache, which I’m pretty sure doesn’t care about the referrer field, so the end result would have been, depending on the moment the cache was filled, either everyone got the message or nobody did, which doesn’t really help things.
I went for something quick and dirty that might not catch everyone, but it’s more than enough to meet my immediate goals – you’re welcome to expand on my solution, and hey, leave a comment if you do!
Somewhere else on the page you’ll have a div with an inline style=’display:none;’ in it with the id that you’ll fill into the id_of_your_div spot above. As I mentioned earlier, we default to display:none because there are some browsers that won’t be able to handle this for various reasons, so it’s better not to show them the special-case message if there’s a chance it won’t apply to them.
A few notes:
- You can use this technique for any referrer, not just a specific search term on Google – for example, a “Welcome, Digg user!” banner if you get Dugg.
- I don’t actually check if it’s coming from Google, because I figure some other referrer with a “q=” parameter is probably another search engine and so I lump the treatment all together. Your needs may vary.
- My comparison is case-sensitive, because it’s a single word term and clearly I’m too lazy to add a “.toLowerCase” to the end of my first term.
- When you’re testing this, you might not notice results at all, and that’s very likely because your page is still cached (I don’t know if WP-Cache checks the template file date or not; I did mine with a hook in the Thesis framework [affiliate link] and the cache overrode anything I changed.) To get around this, just edit and update (without changing) the first post on the home page and the cache will reset.