This is working in my WordPress site. Remember we are using the plugin “Per page head”, which allows you to add content into the section for a specific page, like custom JS or custom HTML. This is the custom code added:
<script>// <![CDATA[
jQuery(document).ready(function($){
$('.class-name-of-the-button').click(function() {
ga('send', 'event', {
eventCategory: 'Outbound Link',
eventAction: 'click',
eventLabel: event.target.href,
transport: 'beacon'
});
});
});
// ]]></script>
Explanation:
- We must add a
jQuery(document).ready(function($){
at the beginning - Note: I think
// <![CDATA[
and// ]]>
are not actually needed - As the button takes us to an external website, we should add
eventLabel: event.target.href
as it’s explained here: https://developers.google.com/analytics/devguides/collection/analyticsjs/events - Of course, we can change .class-name-of-the-button to and add to the button an ID like push me, so it would be
$('#mybutton999').click(function() {
- transport: ‘beacon’ delays loading the external URL until it’s send to Google Analytics. But it’s not compatible with all internet browsers.
- Again, more information about eventCategory, eventAction, transport etc. here: https://developers.google.com/analytics/devguides/collection/analyticsjs/events
Finally, notice I have seen in real time in Google Analytics (on Real time – Events) when I have pushed the button to test it.