Tech Blog :: Google Analytics Custom Variables
Google Analytics Custom Variables
I have a need on several projects to use Google Analytics for lists of "Most Popular" content. Drupal's core node_counter stats are DB write-heavy and don't work on sites behind a full-page cache like Varnish or Akamai. So querying the Analytics API for the most popular pages is a good alternative.
Since I last looked into this over a year ago, several modules have filled in big pieces of this. The Google Analytics API module handles API calls. Google Analytics Importer claims to import stats into node_counter, but there’s no code released yet. Google Analytics Tokenizer could be used to put custom tokens into the Analytics tracker. Google Analytics Counter “can extrapolate page view count for cached values” and does a bunch of other stuff. The last one is the most interesting, but it runs on the fly, rather than on cron, which (running every 15 minutes or so) seems to make more sense for a global and relatively real-time list.
Also, none of these modules track the node ID; they use the URL/alias as a proxy. That’s not necessarily a bad approach, but aliases can change, and nid’s would be more direct. Analytics offers five "custom variable" slots, why not use them for core variables like nid, user ID (if it can bypass page caching), and any other backend-set variables? So I wrote a Google Analytics Custom Variables module (on GitHub not drupal.org; I'll gladly push another remote when d.o moves to Git), it sets nid and uid by default and allows the other 3 to be set with a hook. I haven’t been able to test it yet on the Analytics-report side, but I’ve verified that it’s putting the right JS into the page according to the API documentation.
Next step is to use the Google Analytics API module to query the data on cron. I can probably use 90% of the Google Analytics Counter code with some tweaks.
Update: I added a Drupal.org project page pointing to the Github code.
Update 12/7: The module now retrieves node statistics from the custom 'nid' variable.