Drupal and Google Analytics - How to Track Downloads when using the File Entity Module

track downloads google analytics and drupal

Drupal and Google Analytics - How to Track Downloads when using the File Entity Module

If you're using Drupal's Google Analytics module to track visitors to your website, you might assume that the built-in Track downloads option works without a hitch. 

drupal google analytics track downloads

However, you are out of luck if you are using the File Entity module (which is a requirement for the Media module). A quick search of the File Entity module issue queue and you'll find a bunch of posts about why this module seems to be incompatible with Google Analytics download click events. 

Luckily there is a pretty easy workaround. In this post, I'll show you how to add download tracking to files, and how to set up your analytics to track these events. 

This assumes the following:

  1. You've downloaded, enabled, and configured the Google Analytics module to track your website
  2. You're using the File Entity module for fieldable files
  3. You have a custom theme set up with template.php file so we can modify file download links.

Identify the Appropriate Google Analytics Tracking Code

Champion Googler Kyle found this gem online - a gist for tracking downloads:

<a onclick="ga('send', 'event', 'Downloads', 'Click', 'E-book downloaded', '0');" href="http://mysamplesite.com/wp-content/uploads/2015/12/my-free-lead-magnet.pdf">Download Our Guide to Speeding up Your Site</a>

But what does this mean? Looking at the Google Analytics Tracking analytics.js documentation we can start to tease this gist apart. From Google's docs:

Invoking the ga() command queue function with the following function signature will push commands onto the queue to be scheduled for execution once the library is loaded.
Usage: ga(command, [...fields], [fieldsObject])

We want to send a hit to Google Analytics every time a user clicks on a link that is a downloadable file. We can see the 'send' command does just this. The usage for this send command is as follows:

ga('[trackerName.]send', [hitType], [...fields], [fieldsObject]);


The fields that can be specified by the ...fields parameters vary depending on the hit type. For the Hit type 'event' the ...fields are eventCategoryeventActioneventLabeleventValue

So now the gist becomes clear. For the send command and a hit type event, the following fields will be sent to Google Analytics:

eventCategory: Downloads
eventAction: Click
eventLabel: E-book downloaded
eventValue: 0

This is what the links to download a file look like when using the File Entity and File field:

<a type="application/pdf; length=32521" href="/file/37/download?token=VY8shESE">Download</a>

So, we'll need to modify our links to add the ga send command for an event Hit type with the following fields:

<a onclick="ga('send', 'event', 'Downloads', 'Click', 'PDF downloaded', '0');" type="application/pdf; length=32521" href="/file/37/download?token=VY8shESE">Download</a>

Modify template.php to add tracking code

Open up your template.php file in your current active theme. Here we will override the File Entity module's function
file_entity_download_link(), which itself is overriding Drupal's core theme_file_link() function. Search the File Entity module files for theme_file_entity_download_link, and copy and paste that function into your template.php.

function theme_file_entity_download_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $uri = file_entity_download_uri($file);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $uri['options']['attributes']['type'] = $file->filemime . '; length=' . $file->filesize;

  // Provide the default link text.
  if (!isset($variables['text'])) {
    $variables['text'] = t('Download [file:name]');
  }

  // Perform unsanitized token replacement if $uri['options']['html'] is empty
  // since then l() will escape the link text.
  $variables['text'] = token_replace($variables['text'], array('file' => $file), array('clear' => TRUE, 'sanitize' => !empty($uri['options']['html'])));

  $output = '<span class="file">' . $icon . ' ' . l($variables['text'], $uri['path'], $uri['options']);
  $output .= ' ' . '<span class="file-size">(' . format_size($file->filesize) . ')</span>';
  $output .= '</span>';

  return $output;
}

I've also included it above. Replace the theme in the function name with your theme's name (ie the function should now be named MYTHEME_file_entity_download_link). Then we add the tracking code per Google Analytics analytics.js recommendations. We can do that by adding the code to the $uri['options']['attributes'] array:

/**
 * Overrides theme_file_entity_download_load().
 *
 * This is defined in the file entity module, and itself is overriding the
 * core theme_file_link() function.
 *
 * Override it here so we can add Google Analytics tracking to PDFs.
 */
function MYTHEME_file_entity_download_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $uri = file_entity_download_uri($file);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $uri['options']['attributes']['type'] = $file->filemime . '; length=' . $file->filesize;

  // Add GA tracking for downloads.
  $uri['options']['attributes']['onclick'] = "ga('send', 'event', 'Downloads', 'Click', 'PDF downloaded', '0');";

  // Provide the default link text.
  if (!isset($variables['text'])) {
    $variables['text'] = t('Download [file:name]');
  }

  // Perform unsanitized token replacement if $uri['options']['html'] is empty
  // since then l() will escape the link text.
  $variables['text'] = token_replace($variables['text'], array('file' => $file), array('clear' => TRUE, 'sanitize' => !empty($uri['options']['html'])));

  $output = '<span class="file">' . $icon . ' ' . l($variables['text'], $uri['path'], $uri['options']);
  $output .= ' ' . '<span class="file-size">(' . format_size($file->filesize) . ')</span>';
  $output .= '</span>';

  return $output;
}

Now clear cache and refresh your page - you'll see that all files now have the tracking code for downloads.

Set up Google Analytics to Report on Downloads

Lastly we have to navigate the maze that is Google Analytics administration. There are probably lots of ways to skin this cat, but here is a quick way to track downloads using your custom send event. Log in to your Google Analytics account and head over to the Customizations tab:

Google Analytics dashboard customizations

Under Custom reports, click the New Custom Report button:

Google Analytics create new custom report

Give your custom report a descriptive title, and select Type: Flat Table. Add the necessary dimensions (Page, Event Label, Page Title, Event Action, Event Category) and metrics (Users, Total Events) to your Report Tab as well per the screenshot below:

Google Analytics PDF Download custom report configuration

Save your custom report, and then click/download the crap out of your website once the code is updated with the tracking code. In 24 hours, come back to your Google Analytics account, check out your custom report, and you should see all of your clicks and downloads tracked.

events tracked

You can see that both clicks of Outbound links as well as Downloads are being tracked. If you only want to see Downloads in this custom report, edit your report and add a custom filter to only track events labeled with PDF downloaded. 

add filter to only track downloads

Save and then view your report again. Only the PDF downloads will now be reported. 

Related Posts

Track Contact Form 7 with Google Analytics Goals the Easy Way

Tom McCracken
Read more

A Simple Entity Data API for Module Builders

Tom McCracken
Read more

Creating Custom Google Analytics Events In Drupal

Tom McCracken
Read more

Managing Google Analytics Goals in Drupal

Tom McCracken
Read more

Video: Valuate Content Using Google Analytics and Drupal

Kylon Gustin
Read more

Five Essential Features of Google Analytics

Colin
Read more