Reputation: 11
I have the following in my Wordpress page.php template:
<a role="button" onclick="<?php echo $link['analytics']; ?>" href="<?php echo $link['link']; ?>" target="<?php echo $link['target']; ?>" class="btn btn-large btn-<?php echo $link['color']; ?>">
<i class="icon-white icon-<?php echo $link['icon']; ?>"></i>
<?php echo $link['link_text']; ?>
</a>
The resulting source code looks like this:
<a role="button" onclick="ga('send', 'event', 'button', 'click', ‘itunes')" href="http://itunes.apple.com/us/app/rescue-field-guide/id426955029?mt=8&ls=1" target="_blank" class="btn btn-large btn-primary">
<i class="icon-white icon-download"></i>
Download from the App Store </a>
<a role="button" onclick="ga('send', 'event', 'button', 'click', 'google-play’)" href="https://market.android.com/details?id=com.cmc_rescue.rescue_field_guide&feature=search_result" target="_blank" class="btn btn-large btn-success">
<i class="icon-white icon-download"></i>
Download from Google Play </a>
The links appear like buttons due to the styling which is what I want and they successfully redirect to their respective pages, but they don't register as clicks in my GA account.
How can I get both parts of this functionality working; redirect and onclick?
From my review of these other questions:
Html anchor tag onclick() and href execute simultaneously
HTML anchor link - href and onclick both?
it appears there may be a variety of ways to go about this. What is the simplest way to accomplish this for my scenario? Can I do this without using a separate javascript function or is there an issue with my google analytics function?
Thanks!
Upvotes: 1
Views: 3017
Reputation: 11
Here is what worked after reading the link Andreas sent, thank you!
I changed my approach and placed a jquery script in the head section:
<script>
$(function() { $("a.tracked").click(function(e)
{ if (!ga.q) { var url = $(this).attr("href");
ga('send', 'event', 'outbound', 'click', url, {'hitCallback':
function () { document.location = url; } });
e.preventDefault(); } }); });
</script>
Then in my page.php, I put a css class called "tracked" in the tag.
<a role="button" href="<?php echo $link['link']; ?>" target="<?php echo $link['target']; ?>" class="tracked btn btn-large btn-<?php echo $link['color']; ?>">
<i class="icon-white icon-<?php echo $link['icon']; ?>"></i>
<?php echo $link['link_text']; ?>
</a>
Upvotes: 0
Reputation: 9154
This won't work because ga
submits events asynchronously. Since in your scenario, a new page is loaded immediately afterwards, the events will be lost. Here is a discussion about how to make this work properly:
http://veithen.github.io/2015/01/24/outbound-link-tracking.html
Upvotes: 1