Drupal

Tracking Drupal's Fivestar with Google Analytics

Google Analytics can track more than just page views! Here's a simple Drupal module that records an event when a visitor rates content with Fivestar.


Filed under:

Google Analytics can track more than just page views! Here's a simple Drupal module that records an event when a visitor rates content with Fivestar.

fivestar_ga.js

/**
 * @file
 * Records a google analytics event when a fivestar rating is made.
 */
 
Drupal.behaviors.fivestarGA = function(context) {
  $('.fivestar-widget .star', context).click(function() {
    $form = $(this).parents('form');
    var contentPath = $("[name=content_path]", $form).val();
    var rating = $(this).parent().find('.star').index(this) + 1;
    _gaq.push(['_trackEvent', 'Rating',
      rating + ' star', contentPath]);
  });
};

fivestar_ga.module

<?php
/**
 * Fivestar / Google Analytics integration.
 */
 
/**
 * Implements hook_form_alter().
 */
function fivestar_ga_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'fivestar_custom_widget' ||
    strstr($form_id, 'fivestar_form_node_')) {
 
    // Store the content path in the rating form.
    // This will be used later as an identifier for the event.
    if ($form['content_type']['#value'] == 'node') {
      $content_path = drupal_get_path_alias('node/' .
        $form['content_id']['#value']);
      $form['content_path'] = array(
        '#type' => 'hidden',
        '#value' => $content_path,
      );
    }
  }
}
 
/**
 * Implements hook_init().
 */
function fivestar_ga_init() {
  if (user_access('rate content')) {
    drupal_add_js(drupal_get_path('module', 'fivestar_ga') .
      '/fivestar_ga.js');
  }
}

Similar posts

Get notified on new marketing insights

Be the first to know about new B2B SaaS Marketing insights to build or refine your marketing function with the tools and knowledge of today’s industry.