【问题标题】:how to add google analytics code in template如何在模板中添加谷歌分析代码
【发布时间】:2021-06-09 10:17:33
【问题描述】:

我有一个名为 abc.php 的模板文件,并且仅将此模板用于 1 页,现在我想在部分中添加 google 转换跟踪代码。如果我在 get_header(); 之前添加代码函数然后它显示在标记之前,如果我放在 get_header() 之后;然后它显示在标签中。

请帮助我,因为我只想将转换代码用于 1 个特定页面,因此我无法在 header.php 中添加此代码

 <?php
  /* Template Name: Cost_Estimation_Result */ 
  ?>
   <!-- Event snippet for Website lead conversion page -->
   <script>
    gtag('event', 'conversion', {'send_to': '*********************'});
   </script>
   <?php
   get_header();
   ?>

【问题讨论】:

  • 你也可以阅读这篇文章:support.google.com/analytics/answer/…
  • 谢谢,但这篇文章并没有解决我的问题
  • 以简单的方式你可以复制标题并只使用它,我们也有一些钩子,你可以在 codex 上搜索它

标签: php wordpress templates google-analytics


【解决方案1】:

添加这个 javascript

var script = document.createElement("script");
    
    
    script.innerHTML = "your analytics code";
    
    // Append to head
    
    document.head.appendChild(script);

试试这个不确定它是否会起作用,如果你从 get_header() 获取字符串并在加载到你的页面之前附加 gtag 部分,就像这样:

  $header = str_get_html(get_header());
    $gtag  = "<script>
    gtag('event', 'conversion', {'send_to': '*********************'});
   </script>";



 $header->find('head', 0)->innertext = $gtag.$header->find('head', 0)->innertext;

参考https://stackoverflow.com/a/18187111/8719734

【讨论】:

  • 感谢您的帮助
【解决方案2】:

在function.php中添加下面的代码解决了我的问题。

 add_action( 'wp_head', 'wpsites_add_tracking_code' );
 function wpsites_add_tracking_code() {
    if ( is_page(200) ) {
       echo'<div class="tracking-code">add your tracking code here.</div>';
    } 
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多