Support

Account

Home Forums Front-end Issues get_field not working in wp_footer

Solved

get_field not working in wp_footer

  • I have a true/false field to allow the end user to enable or disable Google Tag Manager code from being displayed on a per page basis. In this case, the client wants the code to only display on two different pages.

    The following code works perfectly fine when hooked into wp_enqueue_scripts

    function google_tag_manager() { ?>
    
    <?php if ( get_field('enable_google_tag_manager_code') ) { ?>
    <!-- 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','XXX-XXXXXXX');
    </script>
    <!-- Google Tag Manager -->
    <?php } ?>
    
    <?php }
    add_action('wp_enqueue_scripts', 'google_tag_manager' );

    It WILL NOT work when hooked into wp_footer

    function google_tag_manager() { ?>
    
    <?php if ( get_field('enable_google_tag_manager_code') ) { ?>
    <!-- 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','XXX-XXXXXXX');
    </script>
    <!-- Google Tag Manager -->
    <?php } ?>
    
    <?php }
    add_action('wp_footer', 'google_tag_manager' );

    Am I missing something?

  • Figured it out!

    function google_tag_manager() {
    global $wp_query;
    ?>
    <?php if ( get_field('enable_google_tag_manager_code', $wp_query->post->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','XXX-XXXXXXX');
    </script>
    <!-- Google Tag Manager -->
    <?php } ?>
    <?php }
    add_action('wp_footer', 'google_tag_manager' );
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘get_field not working in wp_footer’ is closed to new replies.