skip to Main Content

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

2

Answers


  1. You’re going to want to use admin_enqueue_scripts.

    Something along the lines of:

    function add_gtag_to_admin() {
        wp_enqueue_script(
            'google-analytics',
            'https://www.googletagmanager.com/gtag/js?id=[TAG-ID]',
            array(),
            '1.0.0'
        );
    }
    add_action( 'admin_enqueue_scripts', 'add_gtag_to_admin' );
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search