Helping out visitors from Google

First of all, let me start of by saying that Javascript is not exactly a specialty of mine. I’m competent enough in it, but I’m sure there are folks out there that could implement this much better than I have.

So, on with the show then. Some of you who have been around MT for a couple years now might remember MT-RefSearch. It was, and appears to still be, PHP and MySQL only. Since I use neither of those for my site, it hasn’t been an option for me.

But I have managed to implement it with simple Javascript and a new search template so that it will work for any MT configuration out there (I have only tested it with MT 4 though).

First, the new search template (mt-dir/search_templates/results_json.tmpl):

<$MTHTTPContentType type="text/javascript+json"$>{ "entries": [
  <MTSearchResults>
  { 
    title: '<MTEntryTitle escape_js="1">', 
    permalink: '<MTEntryPermalink escape_js='1'>' 
  },
  </MTSearchResults>
  { }
  ]
}

The last little bit at the end there (the { }) is there since I couldn’t (in my quick search) find a glue-like argument for MTSearchResults, and I needed to not end the JSON array with a comma, so the best solution I could come up with was just stuffing an empty element at the end.

To use this, you need to add/alter a line in your mt-config.cgi file:

AltTemplate json results_json.tmpl

To implement it in my blog’s pages, I added the following to the ‘Sidebar - 3 Column Layout’ template module, at the bottom of the search widget.

<span id="related_search"></span>

You could certainly put it wherever you’d like; that’s just where I chose to place it. Heck, I don’t even think it has to be a span (is that even the correct element?).

And, finally, the Javascript workhorse goes into the ‘Header’ template module:

<script type="text/javascript" src="<MTStaticWebPath>js/mt_core_compact.js"></script>
<script type="text/javascript">
function mt_search_cb (txt) {
  var obj = eval ("(" + txt + ")");
  if (obj.entries.length == 1) {
    return;
  }

  var elem = document.getElementById ('related_search');
  var str = '<ul>';
  for (var i = 0; i < obj.entries.length - 1; i++) {
    str = str + '<li><a href="' + obj.entries[i].permalink + '">' + obj.entries[i].title + '</a></li>';
  }
  str = str + '</ul>';
  elem.innerHTML = '';
  elem.innerHTML = str;
}

function checkReferer () {
  if (document.referrer.indexOf ('google') != -1 && document.referrer.indexOf('q=') != -1) {
    var queryTermsRegExp = new RegExp('q=([^&]+)');
    if (queryTermsRegExp.test(document.referrer)) {
      var q = RegExp.$1;
      Client.simpleRequest ('<MTCGIPath><MTSearchScript>', { 'search': q, 'Template': 'json', 'IncludeBlogs': <MTBlogID> }, mt_search_cb);
    }
  }
}

TC.attachLoadEvent (checkReferer);
</script>

Google Referrer

So, if a visitor comes in from a google search, an unordered list of entries that match the search term will show up beneath the search form. It’s not pretty, but it at least illustrates my point.

Enjoy!

1 TrackBack

Всегда приятно, когда при переходишь по ссылке с поисковика и обнаруживаешь на странице искомые слова, которые выделены в тексте. Дэвид Рэйнерс написал, как сделать подобное при помощи одного лишь javascript (обычно используется PHP & MySQL). ... Read More

1 Comment

Hi David, this looks great. Could you bundle up the example code since it's not being displayed fully in the post? I'd really like to try it out.

Thanks!

Leave a comment

About Me

I am a software developer for Six Apart living outside of Baltimore, MD. I have written a number of plugins for Movable Type, including the award winning MultiBlog, which has (as of MT 4) been integrated into the base application....
More...

Recent Entries

  • The Olympics Make Me Want To Complete Again

    Every time the Olympics come around (most the summer ones) I always start to delude myself into thinking I could complete once again in the...

  • Minimalist plugins are fun!

    Last night I whipped up one of the smallest plugins I’ve ever written. It is so small in fact that I was able to stuff...

  • Feedburner Widget on MT News

    Movable Type News A WordPress 2.5 Upgrade Guide: And of course there are lots of third-party plugins for the MT dashboard, to integrate statistics and...

  • AD&D Monster Stats for the Presidential Canditates

    Charles Stross (scifi author, D&D nerd, and former perl columnist) posted Politics as she is Played with 3d6: The recent death of Gary Gygax, who...

  • Feedburner Widget 0.3

    At this point, I am really tempted to drop the ‘Widget’ from the name of the plugin, since it is doing so much more...

Close