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

在WordPress的wp_footer动作中如何在script标签内使用JavaScript变量

代码修复说明

你当前的代码存在两处需要调整的逻辑:

  • document.querySelector('meta[property~="og:type"]')获取到的是meta标签的DOM元素对象,并不是标签对应的content内容,需要额外取元素的content属性才能拿到你需要的og:type值
  • 缺少空值兼容逻辑,如果页面没有对应meta标签,直接取属性会抛出JS异常

修正后可用代码

add_action('wp_footer', 'mather_script');

function mather_script(){
   echo "
    <script> 
       var typeEl = document.querySelector('meta[property=\"og:type\"]');
       var type = typeEl ? typeEl.content : 'unknown';

       window.dataLayer = window.dataLayer || [];
       dataLayer.push({
         pageType: type
       });
    </script>";
}

如果你的页面不需要兼容IE等老旧浏览器,也可以用可选链语法简化取值逻辑:
var type = document.querySelector('meta[property=\"og:type\"]')?.content || 'unknown';

修改后即可正确将og:type的实际内容赋值给pageType字段推入dataLayer。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 01:06:03