You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress edit.php后台页面添加GTM脚本并修复CSP错误

解决WordPress后台添加GTM脚本的CSP错误

错误原因

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.

这个错误说明你的站点**Content Security Policy(CSP)**规则未允许从https://www.googletagmanager.com加载外部脚本,当前的script-src指令仅信任本站资源、内联脚本和eval脚本,因此浏览器拒绝加载GTM脚本。

解决方案

在自定义插件中添加以下代码,分两步完成:

1. 修改CSP头以允许GTM域名

使用wp_headers钩子调整CSP规则,将GTM的域名加入script-src允许列表:

add_filter('wp_headers', 'allow_gtm_csp_header');
function allow_gtm_csp_header($headers) {
    // 检查是否已存在CSP头
    if (isset($headers['Content-Security-Policy'])) {
        // 在现有script-src规则后追加GTM域名
        $headers['Content-Security-Policy'] = str_replace(
            "script-src 'self' 'unsafe-inline' 'unsafe-eval'",
            "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com",
            $headers['Content-Security-Policy']
        );
    } else {
        // 若站点未设置CSP,直接生成包含GTM的基础规则
        $headers['Content-Security-Policy'] = "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com; object-src 'none';";
    }
    return $headers;
}

2. 修正脚本加载逻辑(确保当前页面判断正确)

原代码中$current_page的获取可能不准确,改用WordPress官方的get_current_screen()函数判断后台页面,同时补充GTM的初始化脚本:

add_action('admin_enqueue_scripts', 'enqueue_gtm_script');
function enqueue_gtm_script() {
    $screen = get_current_screen();
    $target_pages = array("edit", "post", "edit-tags");
    
    // 验证当前后台页面是否在目标列表中
    if ($screen && in_array($screen->base, $target_pages, true)) {
        // 加载GTM的gtag.js脚本
        wp_enqueue_script(
            'google-analytics',
            'https://www.googletagmanager.com/gtag/js?id=[TAG-ID]',
            array(),
            '1.0.0',
            false // 设为false在<head>中加载,符合GTM的加载要求
        );
        
        // 添加GTM初始化的内联脚本
        wp_add_inline_script(
            'google-analytics',
            "window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '[TAG-ID]');",
            'after'
        );
    }
}

注意事项

  • 将代码中的[TAG-ID]替换为你实际的GTM/GA跟踪ID。
  • 如果你的站点使用安全插件(如Wordfence、iThemes Security)或主机服务商已配置CSP,需在对应插件/主机面板中修改CSP规则,这些设置会优先覆盖钩子添加的HTTP头。
  • 测试前清空浏览器缓存,确保新的CSP规则生效。

内容的提问来源于stack exchange,提问作者Manav Chauhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:21:02