如何在模板中添加谷歌分析代码

时间:2021-06-09 10:17:33

标签: php wordpress templates google-analytics

我有一个名为 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();
   ?>

2 个答案:

答案 0 :(得分:0)

添加这个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

答案 1 :(得分:0)

在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>';
    } 
  }