Google Analytics Helper for CodeIgniter


/ Published in: PHP
Save to your folder(s)

Below are two functions I've been using to make event tracking a little easier in CodeIgniter.

Two functions are available, google_analytics() & track_event().

google_analytics() takes one argument and uses it as the UA code for your tracking profile. track_event has two required parameters, $category and $event. The other two items are optional and won't be inserted unless specified.

Usage is pretty straight-forward:



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. #
  4. # Google Analytics Code
  5. #
  6.  
  7. if ( ! function_exists('google_analytics'))
  8. {
  9. function google_analytics($account)
  10. {
  11. $code = "<script src='http://www.google-analytics.com/ga.js' type='text/javascript'>";
  12. $code .= '<script type="text/javascript">';
  13. $code .= ' try{ ';
  14. $code .= ' var pageTracker = _gat._getTracker("'.$account.'"); ';
  15. $code .= ' pageTracker._trackPageview(); ';
  16. $code .= ' } catch(err) {} ';
  17. $code .= '</script>';
  18.  
  19. return $code;
  20. }
  21. }
  22.  
  23. #
  24. # Event Tracking
  25. #
  26.  
  27. if ( ! function_exists('track_event'))
  28. {
  29. function track_event($category, $action, $label = '', $value = '')
  30. {
  31. $code = 'pageTracker._trackEvent(';
  32. $code .= "category = '$category' ";
  33. $code .= "action = '$action' ";
  34.  
  35. $code .= ( $label == '' ) ? '' : "label ='$label'";
  36. $code .= ( $value == '' ) ? '' : "value ='$value'";
  37.  
  38. $code .= ');';
  39.  
  40. return $code;
  41. }
  42. }

URL: http://brettbergeron.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.