CakePHP: Simple Google Analytics integration

The easiest way to integrate Google Analytics’ JavaScript tracking code in your cake application is to add Google’s code snippet in the file app/views/default.ctp.

To be a little more flexible you can store the tracker code in the application’s configuration file (/app/config/core.php). Moreover you can define a CakePHP (view) element that can be reused in other CakePHP projects.

Howto / source code:

  1. Define the view element (app/views/elements/google-analytics.ctp):
    <?php
    $gaCode = Configure::read('google-analytics.tracker-code');
    if ($gaCode) {
    $googleAnalytics = <<<EOD
    <script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    </script>
    <script type="text/javascript">
    try {
    var pageTracker = _gat._getTracker("$gaCode");
    pageTracker._trackPageview();
    } catch(err) {}</script>
    EOD;
    echo $googleAnalytics;
    }
    ?>
  2. Include the view element in app/views/default.ctp (just before </body>):
    <?php echo $this->element('google-analytics'); ?>
  3. Define the tracker code in the configuration (/app/config/core.php):
    Configure::write('google-analytics.tracker-code', false); // disables Google Analytics
    Configure::write('google-analytics.tracker-code', 'YOUR-TRACKING-CODE'); // enables Google Analytics

Comments

  1. Farhan

    Good work, nice and easy for quick integration. I will use this soon!

  2. Heiner

    Nice Hint! Btw consider this: http://goo.gl/ybO0

  3. Andrzej

    Thank you very much!!! It is a very usefull tip.

  4. Ivan

    Any update to this now – for analytics with domain?

  5. Dave Knight

    this is good, but you can just add the script code google gives you to the app/view/element/footer/footer.ctp file in one shot. works well, and less involved.

  6. Dawid

    Many thanks Dave. That’s what I was looking for 🙂

  7. Sumit

    I have a script code provided by google. How can I integrate google analytics in my cake php website ?

Leave a comment

Your email address will not be published. Required fields are marked *

*