A better way of using Google analytics with Moodle.

View more Presentations from Bas Brands

At the Ireland & UK Moodlemoot we presented on the Google-Analytics reporting we had implemented for the Moodlemoot site. Over on his blog, Gavin explains/shows on his post(link), you can do nice reports with G-A however this requires some changes to Moodle. This post will focus on what we code we used and how it works to achieve that type of reporting.

The problem with Moodle are links that are formatted like this:

http://www.mymoodlesite.org/course/view.php?id=5
http://www.mymoodlesite.org/mod/forum/view.php?id=80

When you would actually like to have links like this:

http://www.mymoodlesite.org/CategoryA/sourcialcourse/Topic+1/myresource
http://www.mymoodlesite.org/Category1/introcourse/Topic+3/open+forum/Forum

How to get it done? Add a new file to your theme,  for instance: /js/google-analytics.php and paste in this code. Make sure you insert your unique Google Analytics key

<?php

$trackurl = '';
$gakey = 'ENTER YOUR GA KEY'

global $DB;
if ($COURSE->id != 1 ){

    //Add course category name
    if ($category = $DB->get_record('course_categories',array('id'=>$COURSE->category))){
        $trackurl .= '/' . urlencode($category->name);
    }

    //Add course name
    $trackurl .= '/' . urlencode($COURSE->shortname);
}

//Use navigation bar to get items
$navbar = $OUTPUT->page->navbar->get_items();

//remove first item (home)
$first = array_shift($navbar);

foreach ($navbar as $item) {
    //get section name
    if ($item->type == "30") {
        $trackurl .= '/' . urlencode($item->title) ;
    }
    //get activity type
    if ($item->type == "40") {
        $trackurl .= '/' . urlencode($item->text) ;
        $trackurl .= '/' . urlencode($item->title) ;
    }
    //get action type
    if ($item->type == "60") {
        $trackurl .= '/' . urlencode($item->title) ;
    }
}
//for debugging
//echo $trackurl;

?>
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '<?php echo $gakey;?>']);
  _gaq.push(['_trackPageview','<?php echo $trackurl;?>']);

  (function() {
    var ga = document.createElement('script');
    ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +
    '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
  })();
</script>

Now in your theme layout files add this line in the head:

<?php include($CFG->dirroot . "/theme/YOURTHEMENAME/js/google_analytics.php"); ?>

Future plans? Get data back from Google Analytics into Moodle Add more variables Send data on event triggers

Get involved?

Send us a message on twitter! or send an email