Web Analytics

Oct 17 2009

Google Analytics Goal Pages with CakePHP

View comments

For those of you who are using Google Analytics (GA) goals with CakePHP, I'm going to show you how you can use some server-side scripting through the CakePHP controller to write some Javascript for GA.

To set up a goal in GA, you have to tell GA which page should be considered the goal page, and it's usually a receipt page or a thank you page. So for example, if you have a contact form (/contact) on your site like I do, and you wanted to set that up as a goal, you'd have to create a new thank you page (/contact/thanks)  and redirect there upon form submission. This is a problem because, although unlikely, the user could potentially bookmark that page and come back in another visit, causing additional goal conversions. Other than that, it's just a useless, static page and creates more work for you.

Instead, I recommend the following technique.

Create the element

  1. Put your GA Javascript tracking code in an element ga.ctp.
  2. Change the _trackPageview() line to:
    pageTracker._trackPageview(<?if ($pageURL) echo "'$pageURL'";?>);

    This will allow us to specify custom page URLs from the controller and give it to GA.

Render the element

  1. In your layout file, put the following PHP code before your closing </body> tag to render the ga.ctp element:
    <?=$this->element('ga',array('pageURL'=>@$pageURL));?>

Modify the controller

  1. In your controller, wherever you have the success part of your function and wherever you would normally redirect to the thank you page, change it to this:
    $this->set('pageURL', '/contact/thanks');
    $this->Session->setFlash('Thank you, your message has been sent!');

    Here we are setting $pageURL to /contact/thanks, that will be fed to the view/layout, and finally it will be fed to our ga.ctp element which will put it where we want.

That's it!

By using this technique and by letting the controller set the page URL upon success, you don't need to create a separate, useless thank you page, and you don't have to worry about people returning to the page causing additional goal conversions. This technique can be used for ecommerce tracking too. I hope that was helpful. Good luck!