How to add Google Tag Manager to a SPECIFIC WordPress post via Code Snippets?

I’m running Code snippets plugin on WordPress. I want to be able to include Google Tag Manager on only one specific post in my blog. This is because I only care about the outbound events showing up in Analytics for one specific post, and I don’t want GTM to slow down every other page or post just for it.

I have two separate Code Snippets. One for adding GTM to header, which looks like:

if ( is_single('511') ) {
    add_action( 'wp_head', function () { ?>
    <!-- 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-000000');</script>
    <!-- End Google Tag Manager -->
    <?php } );
};

And one for adding GTM to the body open, which looks like:

if ( is_single('511') ) {
    add_action( 'wp_body_open', function () { ?>
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-000000"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
    <?php } );
};

A note on both, the Code Snippets plugin as I understand it, already opens and closes with PHP tags so they aren’t necessary except for inside this code to add HTML to the head and open body functions and then opens PHP again.

I’m checking and re-checking, clearing caches and the code isn’t showing on the page. My GTM code was removed from the code above.

I’m very sketchy with PHP knowledge, what am I missing on my if statement?

I have searched a lot but never finding a specific use-case matching mine to just appear on one post only.

Source: Ask PHP

LEAVE A COMMENT