John
John

Reputation: 10146

Google Analytics tracking events within php

I want to track events via google analytics for items loading on the page. Basically if a banner image shows on a page I want to track the impression via an event using google analytics. So for example:

pageTracker._trackEvent('BannerImages','Impression','Banner Ad Name Here');

Where would I put this? Here is the php code:

$query = $dbconn->query("SELECT * FROM banner_images LIMIT 5");

foreach($query AS $banner_result)
{

echo '<div>' .$banner_result->location .'</div>';

}

Would I echo out the pageTracker code after each value is echoed out for $banner_result->location like so?

echo '<div>' .$banner_result->location .'<div>' ."\n" .'<script>pageTracker._trackEvent('BannerImages','Impression','Banner Ad Name Here');</script>';

The google tracking code is in the footer.

EDIT

Looks like I have to add it after the tracking code initializes.

Upvotes: 0

Views: 2212

Answers (1)

konsolenfreddy
konsolenfreddy

Reputation: 9671

I would collect all pageTracker items in an array

foreach($query AS $banner_result){
    echo '<div>' .$banner_result->location .'</div>';
    $googleAnalytics[] = "pageTracker._trackEvent('BannerImages','Impression','".$banner_result->yourBannerName."');";
}

And add them after you included the async Google Analytics code:

echo '<script>'.implode("\n",$googleAnalytics).'</script>';

Upvotes: 2

Related Questions