0

I use following way to fetch the value of gtag if it already exists in the code:

        <script>
        const regex = /googletagmanager\.com\/gtag\/js\?id=([^\s'"]+)/gi;

        const scriptTags = document.querySelectorAll('script');
                let trackingID = ''; 
                scriptTags.forEach(script => {
                    const src = script.getAttribute('src');
                     if (src && src.includes('googletagmanager.com/gtag/js')) {
                        const match = regex.exec(src);
                     if (match && match.length > 1) {
                        trackingID = match[1];
                     }
                   }
                });
        </script>

Now I want the trackingID to be printed in the following script if it exists else print the code value that exists

<script async src="<?php echo ( $local_analytics_file ?? 'https://www.googletagmanager.com/gtag/js?id=' ) . '?' . esc_html( $UA_CODE ); ?>"></script>

Need something like

<script async src="<?php echo ( $local_analytics_file ?? 'https://www.googletagmanager.com/gtag/js?id=+if(trackingID) trackingID' ) . '?' . esc_html( $UA_CODE ); ?>"></script>

And similarly in following

<script>
            console.log('Google Analytics Tracking ID:', trackingID);

            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            const configuration = JSON.parse( '<?php echo $configuration; ?>' );
            const gaID = '<?php echo esc_html( $UA_CODE ); ?>'; // I want trackingID to be printed if available else print the $UA_CODE
</script>
3
  • 2
    This isn't possible. You'll need to do it all in JavaScript. Feb 13 at 8:13
  • 1
    Your JS runs on the browser. By that time PHP is all wrapped up. This is not gonna fly.
    – vancoder
    Feb 13 at 22:28
  • any fixes? @vancoder
    – ahmedwp
    Feb 14 at 10:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.