Read URL parameters inside Magento (for tracking)

Feb 19, 2011

You likely want to be able to pass some tracking information about the visitors to your Magento site through to your back-end systems. I usually implement tracking using the same method as Google Analytics, just for convenience. Also, there is a ready-made [URL Builder][1] for clients non-google campaigns. This sends tracking data through to the site but you need a custom module to read those parameters and store them in a cookie. Your order export module can then read the cookie and include that information with the order.

You can intercept a Magento event that is called at the start of every request using this config.xml…

<global>
  <events>
    <controller_front_init_routers>
      <observers>
        <packagename_modulename_observer>
        <type>singleton</type>
        <class>Packagename_Modulename_Model_Observer</class>
        <method>interceptMethodNameCanBeAnything</method>
        </packagename_modulename_observer>
      </observers>
    </controller_front_init_routers>
  </events>
</global>

And then in the method you specify you can…

public function interceptMethodNameCanBeAnything($observer) {
    $request = $observer->getEvent()->getData('front')->getRequest();
    $utm_source = $request->utm_source;

    //do whatever you want with your variable here
}

[1]: https://support.google.com/analytics/answer/55578?hl=en