admin管理员组

文章数量:1125040

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

        <script>
        const regex = /googletagmanager\\/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/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 ?? '=' ) . '?' . esc_html( $UA_CODE ); ?>"></script>

Need something like

<script async src="<?php echo ( $local_analytics_file ?? '=+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>

本文标签: how to assign javascript variable value to php variable in wordpress