We need to add some enhanced ecommerce tags to standard Google Analytics tracking on few pages. We think the best way to do it would be to use Joomla Custom fields so we created a custom field for testing:
The custom field is:
ID: '1' Name: 'ec-js'
Automatic display - off
type: text filter: no
Show on: both
value (in one article; for testing): 'ga('require', 'ec');'
The template is Yootheme Infinite (Warp 6 based). We put the custom code in 'template.php', not in article override because we need it on every page including /search etc. So far we have tried:
<?php
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
$jcFields = FieldsHelper::getFields('com_content.article', $item, true);
$itemCustomFields = array();
foreach($jcFields as $field) {
$itemCustomFields[$field->name] = $field;
}?>
and then in body:
<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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxx', 'auto');
ga('require','displayfeatures');
<?php echo $article->itemCustomFields['ec-js']->value; ?>
ga('send', 'pageview');
</script>
The main GA code is displayed on all pages.
The problem is that the contents of the custom field are not displayed on the test page containing the value - the override is clearly not working.
Help with this would be appreciated.
UPDATE - 13/04/2018
I have made some good progress...
I override article default.php with the following PHP:
$CCFields = array();
foreach($this->item->jcfields as $field) {
$CCFields[$field->name] = $field->value;
}
$GLOBALS['CCFields'] = $CCFields;
then add to template.php:
<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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxx', 'auto');
ga('require','displayfeatures');
<?php echo $GLOBALS['CCFields']['ec-js'] ?>
ga('send', 'pageview');
</script>
The result is GA JS with enhanced ecommerce tags nicely injected when needed - only with caching disabled.
If I enable Joomla cache (conservative) the 'ec-js' field is not longer injected meaning the values of $GLOBALS['CCFields'] are not cached and are only available on 1st page load. Any successive page load e.g. 2nd or 3rd results in nothing injected as content of the array is not cached.
How do I make contents of $GLOBALS['CCFields'] cached?
Thanks.