• zanddatis

    (@zanddatis)


    I wanna add TagManager Script in my site.

    I active Child Theme, How can i do it?

    I try this, but i have erorr: for ex add to body

    add_action('wp_head', function() {
    // Your HTML Code / Example
    ?>
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/000000000000000000"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
    <?php
    });
Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi @zanddatis
    Thanks for reaching out us at the WordPress.org support forum, we are happy to assist you with any issue you may be experiencing.

    wp_head hook prints scripts or data in the <head> tag on the front end, that’s the reason you encounter that error. I please use the wp_footer hook instead, which will print your scripts inside the <body> tag.

    Let me know if this resolves your issue.

    Regards,
    Mashiur R.

    mayuripatel

    (@mayuripatel)

    Hello

    Add the GTM script inside the <head> section using the wp_head hook

    The noscript part should be added right after the opening tag, but this requires using the wp_body_open action

    you can add below code in functions.php file in your child theme .

    // Add Google Tag Manager (GTM) script to the <head> section
    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-XXXX');</script>
    <!-- End Google Tag Manager -->
    <?php
    });

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

    Ensure that you have the right container ID (replace GTM-XXXX).

    Ensure your theme supports the wp_body_open action (introduced in WordPress 5.2). If it’s not supported in your theme, you may need to manually add it right after in your theme’s header.php file like so:

    <?php do_action( 'wp_body_open' ); ?>

    Thanks

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘add script in body and head by child’ is closed to new replies.