Home / Admin / GTM Injection + Expose login state via .php
Duplicate Snippet

Embed Snippet on Your Site

GTM Injection + Expose login state via .php

Do not inject GTM via Header Footer if using this php snippet

Code Preview
php
<?php
/**
 * GTM injection with admin exclusion (WordPress)
 * - Admins (manage_options) get NO GTM at all
 * - Everyone else gets GTM head + noscript
 * - Exposes login/admin state to the browser early
 */
if ( ! defined( 'GTM_ID' ) ) {
    define( 'GTM_ID', 'GTM-XXXXXXX' );
}
/**
 * Determine whether GTM should load.
 */
function moco_should_load_gtm() {
    if ( ! is_user_logged_in() ) {
        return true;
    }
    // Exclude administrators
    if ( current_user_can( 'manage_options' ) ) {
        return false;
    }
    return true;
}
/**
 * Expose login/admin state early.
 */
add_action( 'wp_head', function () {
    $is_logged_in = is_user_logged_in() ? 'true' : 'false';
    $is_admin    = ( is_user_logged_in() && current_user_can( 'manage_options' ) ) ? 'true' : 'false';
    echo '<script>';
    echo 'window.wpUserLoggedIn=' . $is_logged_in . ';';
    echo 'window.wpUserIsAdmin=' . $is_admin . ';';
    echo '</script>';
}, 1 );
/**
 * GTM <head> script
 */
add_action( 'wp_head', function () {
    if ( ! moco_should_load_gtm() ) {
        return;
    }
    ?>
    <!-- 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 esc_js( GTM_ID ); ?>');
    </script>
    <!-- End Google Tag Manager -->
    <?php
}, 20 );
/**
 * GTM noscript (right after <body>)
 */
add_action( 'wp_body_open', function () {
    if ( ! moco_should_load_gtm() ) {
        return;
    }
    ?>
    <!-- Google Tag Manager (noscript) -->
    <noscript>
      <iframe src="https://www.googletagmanager.com/ns.html?id=<?php echo esc_attr( GTM_ID ); ?>"
              height="0" width="0" style="display:none;visibility:hidden"></iframe>
    </noscript>
    <!-- End Google Tag Manager (noscript) -->
    <?php
}, 1 );

Comments

Add a Comment