
Drupal 7 - Theming phone numbers with Google Analytics code
Published: 5/20/2016
We use Google Analytics to track all of the usual stuff, but my PR folks also wanted track phone number link clicks from mobile devices. In order to do that, Google has code (something like the following) that has to be added around a clickable phone number.
onclick="ga('send', 'event', 'Call', 'Call', '800-888-8888')"
This is fine if you're adding a phone number to a body field or a static block. But many of my phone numbers are their own field in various content types. Or they're displayed through Views.
Thinking that those in Views would be easy, I started with them, and attempted to rewrite the results of my phone number fields to include the onclick. But views stripped away the Javascript no matter what input format I used. I read enough to articles to realize it wasn't just me, although I found conflicting opinions about whether the Javascript removal was correct Views behavior. I aslso briefly looked at the GA Push Module (opens in new tab), but I typically try to find a solution that doesn't involve installing ANOTHER module.
So I decided to theme my phone number fields (named 'Mobile Dial' and 'Telephone').
First I copied field.tpl.php and placed it in /sites/all/themes/<theme name>/templates. I renamed the file field--field-mobile-dial.tpl.php and replaced the existing code with this:
?>
<?php foreach ($items as $delta => $item) : ?>
<a href="tel:<?php print render($item); ?>" onclick="ga('send', 'event', 'Call', 'Call', '<?php print render($item); ?>');"><?php print render($item); ?></a>
<?php endforeach; ?>
Secondly, I had a view named 'locations' that displayed only 2 fields: a Title and the Telephone field. Since there were only 2 fields in the view, I decided to theme the whole view, and I used the file views-view-fields.tpl.php. I copied it to /sites/all/themes/<theme name>/templates and named it views-view-fields--locations--block.tpl.php (because there was only one view display, which was 'block'). I replaced the existing code with this:
?>
<?php print $fields['title']->content ?><br>
<a href="<?php print $row->field_field_telephone[0]['rendered']['#href']; ?>" onclick="ga('send', 'event', 'Call', 'Call', '<?php print $row->field_field_telephone[0]['rendered']['#href']; ?>');"><?php print $row->field_field_telephone[0]['rendered']['#title']; ?> </a>
These two changes allowed us to track phone number clicks from mobile devices within Google Analytics without installing any new modules.
