Skip to content

Commit

Permalink
Merge pull request #6 from ministryofjustice/gtm
Browse files Browse the repository at this point in the history
Add site analytic support using Google Tag Manager
  • Loading branch information
brown-a2 authored Aug 14, 2020
2 parents 1f728c9 + 9ff7b5b commit eb02ac8
Show file tree
Hide file tree
Showing 3 changed files with 182 additions and 3 deletions.
80 changes: 80 additions & 0 deletions component/Analytics/Analytics.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace component;

use component\Analytics\AnalyticsSettings as Settings;

class Analytics
{
/**
* @var string
*/
public $parentPath = '';

/**
* @var boolean
*/
public $hasSettings = true;

/**
* @var object
*/
public $settings;

/**
* @var string
*/
public $googleTagManagerID;

public function __construct()
{
$this->settings = new Settings();

$this->actions();

// Get GTM ID if provided via the settings field
$options = get_option('moj_component_settings');
$this->googleTagManagerID = $options['gtm_analytics_id'] ?? '';
}

public function actions()
{
add_action('wp_loaded', [$this->settings, 'settings'], 1);
add_action('wp_head', [$this,'loadGoogleTagManagerInHead']);
add_action('wp_body_open', [$this,'loadGoogleTagManagerInBody']);
}

/**
* Add code as per Google guidance.
*
* https://developers.google.com/tag-manager/quickstart
*/
public function loadGoogleTagManagerInHead()
{

// We only want to display GTM code when an ID has been entered.
if (!empty($this->googleTagManagerID)) {
?>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer', '<?php echo sanitize_html_class($this->googleTagManagerID); ?>' );</script>
<!-- End Google Tag Manager -->
<?php
}
}

public function loadGoogleTagManagerInBody()
{
if (!empty($this->googleTagManagerID)) {
?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=<?php echo sanitize_html_class($this->googleTagManagerID); ?>"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php
}
}
}
83 changes: 83 additions & 0 deletions component/Analytics/AnalyticsSettings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

namespace component\Analytics;

use component\Analytics as Analytics;

class AnalyticsSettings extends Analytics
{
public $helper;

public function __construct()
{
global $mojHelper;
$this->helper = $mojHelper;
}

public function settings()
{
$this->helper->initSettings($this);
}

public function settingsFields($section)
{
add_settings_field(
'gtm_analytics_id',
__('GTM ID', 'wp-moj-components'),
[$this, 'setGoogleTagManagerID'],
'mojComponentSettings',
$section
);
}

/**
* Function that collects inputed GTM ID and running checks on it.
*/
public function setGoogleTagManagerID()
{
$options = get_option('moj_component_settings');
$googleTagManagerID = $options['gtm_analytics_id'] ?? '';

?>
<input type='text' name='moj_component_settings[gtm_analytics_id]'
placeholder="GTM-XXXXXXX" value='<?php echo sanitize_html_class($googleTagManagerID); ?>'
class="moj-component-input">
<?php

// Run a few basic checks (mainly for devs in case of C&P typos)

// Check if empty string stop rest of checks.
if ($googleTagManagerID === '') return;

// Remove whitespace, tabs & line ends.
$googleTagManagerID = preg_replace('/\s+/', '', $googleTagManagerID);

// Too many, too few characters
if (strlen($googleTagManagerID) != 11) {
echo '<div class="notice notice-error settings-error" style="margin-left: 0;">
GTM ID might be invalid. Double check the charactor count.</div>';
}

// Check it is a GTM ID (not GA for example)
if (!preg_match('/^GTM-/', $googleTagManagerID)) {
echo '<div class="notice notice-error settings-error" style="margin-left: 0;">
GTM ID might be invalid. ID must start with GTM.</div>';
}
}

public function settingsSectionCB()
{
?>
<div class="welcome-panel-column">
<h4><?php _e('Google Tag Manager (GTM)', 'wp_analytics_page') ?></h4>
<p style="max-width: 600px"><?php _e('Analytic tracking on our site is done through GTM.
First setup a GTM account and then add the GTM container ID below and save.
This will add GTM code to the site. You can find the eleven charactor GTM ID, by logining into your GTM account,
in the top right corner of the dashboard.<br><br>If no GTM ID is added, no code is loaded on the page.', 'wp_analytics_page'); ?></p>
<h4><?php _e('Google Analytics (GA)', 'wp_analytics_page') ?></h4>
<p style="max-width: 600px"><?php _e('Add Google Analytics or any other tracker, via the GTM dashboard.',
'wp_analytics_page'); ?></p>
</div>
<?php
}
}
22 changes: 19 additions & 3 deletions wp-moj-components.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
<?php

/**
*
* The file responsible for starting the MoJ Components plugin
*
* This plugin supports common functions needed throughout the JOTW site portfolio.
*
* @package wp-moj-components
*
* Plugin name: WP MoJ Components
* Plugin URI: https://github.com/ministryofjustice/wp-moj-components
* Description: Introduces various functions that are commonly used across the MoJ network of sites
* Version: 3.2.2
* Description: Introduces functions that are commonly used across the MoJ network of sites
* Version: 3.3.0
* Author: Ministry of Justice
* Text domain: wp-moj-components
* Author URI: https://ministryofjustice.github.io/justice-on-the-web/#justice-on-the-web
* License: MIT License
* License URI: https://opensource.org/licenses/MIT
* Copyright: Crown Copyright (c) Ministry of Justice
**/

namespace component;

defined('ABSPATH') || exit;

require_once('component/Introduce/Popup.php');
require_once('component/Versions/Plugins.php');
require_once('component/Introduce/PopupSettings.php');
Expand All @@ -22,8 +34,11 @@
require_once('component/Users/UserSwitch.php');
require_once('component/Sitemap/Sitemap.php');
require_once('component/Sitemap/SitemapSettings.php');
require_once('component/Analytics/Analytics.php');
require_once('component/Analytics/AnalyticsSettings.php');

include_once "load.php";

define('MOJ_COMPONENT_PLUGIN_PATH', __FILE__);

global $mojHelper;
Expand All @@ -37,4 +52,5 @@
new Introduce();
new Security();
new Users();
new Sitemap();
new Sitemap();
new Analytics();

0 comments on commit eb02ac8

Please sign in to comment.