2014-06-22 73 views
1

我想在每個頁面上顯示Google Analytics(分析),但我希望在404模板頁面上顯示略有不同。Google Analytics代碼404錯誤跟蹤WordPress PHP函數文件

我有2個分析代碼。其中一個顯示在每個頁面上。另一種是僅在404頁面上顯示。

這是我正在處理的php代碼被插入到函數文件中。我無法讓它工作。到目前爲止,它所做的只是執行else語句。請幫忙。

if (is_404()) { 
// Include the Google Analytics Tracking Code in 404 
function google_analytics_tracking_code_404(){ ?> 

<script> 
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) 
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 

    ga('create', 'UA-XXXXXXXX-23', 'mydomainname.com'); 
    ga('send', 'pageview', '404/?url='+ document.location.pathname + document.location.search +'&ref=' + document.referrer); 

</script> 

<?php } 

// include tracking code before the closing head tag 
add_action('wp_head', 'google_analytics_tracking_code_404'); 

// OR include tracking code before the closing body tag 
// add_action('wp_footer', 'google_analytics_tracking_code'); 
} 
else { 
// Include the Google Analytics Tracking Code 
function google_analytics_tracking_code(){ ?> 

<script> 
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) 
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 

    ga('create', 'UA-XXXXXXXX-23', 'mydomainname.com'); 
    ga('send', 'pageview'); 

</script> 

<?php } 

// include tracking code before the closing head tag 
add_action('wp_head', 'google_analytics_tracking_code'); 

// OR include tracking code before the closing body tag 
// add_action('wp_footer', 'google_analytics_tracking_code'); 
} 
+0

沒關係我想通了。如果有人需要知道,然後在這裏回覆,我會發布格式化的代碼。 – Mike

回答

1

函數is_404()需要在wp_head的鉤子內部調用。

// Include the Google Analytics Tracking Code in 404 
function google_analytics_tracking_code_404(){ ?> 
    if (is_404()) { ?> 

     <script> 
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) 
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 

      ga('create', 'UA-XXXXXXXX-23', 'mydomainname.com'); 
      ga('send', 'pageview', '404/?url='+ document.location.pathname + document.location.search +'&ref=' + document.referrer); 

     </script> 
    <?php } 
} 

// include tracking code before the closing head tag 
add_action('wp_head', 'google_analytics_tracking_code_404'); 
相關問題