Last active
April 11, 2019 10:17
-
-
Save teej043/2ef56bf8fb836c11d8a07def75abca60 to your computer and use it in GitHub Desktop.
Create Google Analytics field and output with ACF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Google Analytics --> | |
<?php | |
$ga = get_field('site_analytics_ga', 'option'); | |
if ($ga['tracking_code']) : | |
?> | |
<script> | |
(function (i, s, o, g, r, a, m) { | |
i['GoogleAnalyticsObject'] = r; | |
i[r] = i[r] || function () { | |
(i[r].q = i[r].q || []).push(arguments) | |
}, i[r].l = 1 * new Date(); | |
a = s.createElement(o), | |
m = s.getElementsByTagName(o)[0]; | |
a.async = 1; | |
a.src = g; | |
m.parentNode.insertBefore(a, m) | |
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); | |
ga('create', '<?php echo $ga['tracking_code']; ?>', 'auto'); | |
ga('send', 'pageview'); | |
</script> | |
<!-- GA Tracking --> | |
<?php | |
if ( $ga['event_code_generator'] ): | |
?> | |
<script> | |
jQuery(document).ready(function() { | |
// GA Tracking | |
<?php foreach( $ga['event_code_generator'] as $gaEvent ) : | |
$gaCat = $gaEvent['category'] ? ', "' . $gaEvent['category'] . '"' : ''; | |
$gaAct = $gaEvent['action'] ? ', "' . $gaEvent['action'] . '"': ''; | |
$gaLbl = $gaEvent['label'] ? ', "' . $gaEvent['label'] . '"' : ''; | |
$gaIsBounce = $gaEvent['count_as_bounce'] ? ', {"nonInteraction": 1}' : ''; | |
?> | |
jQuery("<?php echo $gaEvent['element']; ?>").on('click', function() { | |
ga("send", "event"<?php echo $gaCat; ?><?php echo $gaAct; ?><?php echo $gaLbl; ?><?php echo $gaIsBounce; ?>); | |
}); | |
<?php endforeach; ?> | |
}); | |
</script> | |
<?php | |
endif; | |
endif; | |
?> | |
<!-- End Google Analytics --> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment