A basic PHP abstraction for Google Tag Manager container and datalayer.
The recommended way to install Tag Manager is through Composer.
$ curl -sS https://getcomposer.org/installer | php
$ composer require shineunited/tagmanager
$ composer.phar update
include(__DIR__ . '/../vendor/autoload.php');
To use Tag Manager with Silex, register the service provider
use ShineUnited\TagManager\Silex\TagManagerServiceProvider();
$app->register(new TagManagerServiceProvider(), [
'gtm.options' => [
'id' => 'GTM-XXXX', //gtm container id (required)
'persist' => true, //persist datalayer in session if true (optional, defaults to false)
'varname' => 'gtm' //session varname (optional, defaults to 'gtm')
]
]);
Adding messages to the datalayer
$app['gtm.datalayer']->push([
'event' => 'gtm.eventName',
'eventData' => [
// event data goes here
]
]);
The extension adds the 'gtm()' function to the Twig environment. Note: the silex service provider will automatically install the twig extension if twig is present.
<html>
<body>
...
{{ gtm() }}
</body>
</html>
Or load the javascript and no-script snippets separately.
<html>
<head>
...
{{ gtm('head') }}
</head>
<body>
{{ gtm('body') }}
...
</body>
</html>