Friday, September 5, 2008

Using Google Analytics to track searches in Drupal

Updated: Added some PHP code to complete the example

Google Analytics needs you to specify part of a query string in order for you to get specialized "Site Search" reports. However in Drupal you might have nice Clean URLs like this:

instead of what GA wants, something like

You can still get Site Search reports for searches using Clean URLs, using the Google Analytics API.

You just need to:

  • Use the "new" GA handling code.
  • Add code like this at the end of your page; I recommend putting it inside a Block (be sure to mark the Input Format to be "PHP code"):

    if (arg(0) == 'apachesolr_search' || arg(0) == 'search') {
    $keys = search_get_keys();
    <script type="text/javascript">
    pageTracker._trackPageview('/site_search?query=<?php echo $keys; ?>');

You then tell your GA report's settings to activate Site Search reporting and to look for "query" as the search argument.

After a day of logging, your GA reports will include the report. See a site searching report sample.


Anonymous said...

thanks...i think. I have implemented the code, but all I am seeing in analytics re: what is being searched is [INSERT CURRENT KEYWORDS HERE]

did I miss something?

Jano said...

Well, actually, you have to get the keywords from Drupal using a bit of PHP. I just updated the post to include the full PHP code and JS to include in a custom block.

ogs22 said...

If you use

under advanced settings it has a 'track search' button

which then adds:

var pageTracker = _gat._getTracker("UA-*****-*");pageTracker._initData();pageTracker._trackPageview("/search/node?search=xxx");

to the page

SEO said...

I never thought that google analytics can really do that. I really want to track searches in drupal and I never thought that google analytics is the answer for it.