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

Recent Entries

  • Must Be Doing Something Right

    It’s not because they say please and thank you so often (and appropriately). It’s not that they hug each other and say they’re sorry (eventually)...

  • Because tests and bugs are fun

    A colleague of mine just shared this particular frustration: yargh. my test passes if all of the objects are created within the same second, but...

  • Upgraded to MT 4.23

    So, yeah, it’s a month late or so, but I’ve been really busy. I finally upgraded this site to Movable Type 4.23. Maybe I’ll even...

  • I apologize about the feed updates

    I’m deploying a development version of my MediaConsumer plugin and a number of entries might appear as updated in feed readers as I start applying...

  • Plugin Writing 101

    So, I’m planning on writing up some entries about various aspects of plugin development. While I have a couple topics already in mind, I thought...

Close