Search code examples
phpwordpresspluginsgoogle-analytics

How can i add a google tag manager script on wordpress edit.php screen?


Here i am trying to add a google tag manager script on wordpress backend edit.php screen but whenever i add a script it gives error in console.

Refused to load the script 'https://www.googletagmanager.com/gtag/js?id=[TAG-ID]&ver=1.0.0' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Here is the code for the same

$func_page = array("edit","post","edit-tags");
if(in_array($current_page, $func_page, true)) {
    wp_enqueue_script(
       'google-analytics',
       'https://www.googletagmanager.com/gtag/js?id=[TAG-ID]',
       array(),
       '1.0.0'
    );
}

please help me how can i fix this issue in my custom plugin


Solution

  • Use the admin_head hook in functions.php file of your theme-

    add_action('admin_head', 'add_script_to_admin_head_section');
    function add_script_to_admin_head_section() {
        global $pagenow;
        if ($pagenow === 'edit.php') {
            ?>
            <!-- START: Google tag manager -->
            <script type="text/javascript">
                // (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-XXXXXXX');
            </script>
            <!-- END: Google tag manager -->
            <?php
        }
    }
    

    Replace the script from to with your GTM script.