Skip to content

Instantly share code, notes, and snippets.

@jamesmthornton
Last active October 15, 2021 19:24
Show Gist options
  • Save jamesmthornton/3e6ea7e818175adc18b5fcfadd5a2a2e to your computer and use it in GitHub Desktop.
Save jamesmthornton/3e6ea7e818175adc18b5fcfadd5a2a2e to your computer and use it in GitHub Desktop.
Add Google Tag Manager to Wordpress and Load Only If An Admin is NOT Logged In
<?php // do not copy this line and make sure to replace "XXXXXXX" with your tag manager ID
// add Google Tag Manager after opening body tag on wordpress (part 1)
add_action( 'wp_head', 'add_custom_google_tag_manager_1', 1 );
function add_custom_google_tag_manager_1() {
// if user is not a logged in admin then load gtm script tag
if( !current_user_can('administrator') ) {
//* replace XXXXXXX with your GTM tracking ID
?><!-- 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','GTM-XXXXXXX');</script><!-- End Google Tag Manager --><?php
}
}
//* add Google Tag Manager after opening body tag on wordpress (part 2)
//* If using genesis replace hook with genesis_before eg. add_action( 'genesis_before', 'add_custom_google_tag_manager_2', 1 );
add_action( 'wp_body_open', 'add_custom_google_tag_manager_2', 1 );
function add_custom_google_tag_manager_2() {
// if user is not a logged in admin then load gtm noscript tag
if( !current_user_can('administrator') ) {
//* replace XXXXXXX with your GTM tracking ID
?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php
}
}
@jamesmthornton
Copy link
Author

Note - this works for MOST wordpress themes. But it assumes that the theme did not strip out the wp_body_open hook, which is required for the second part of GTM tagging to fire immediately after opening tag.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment