我想在每个页面上显示Google Analytics(分析),但我想在404模板页面上显示它稍有不同。
我有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');
}
最佳答案
函数is_404()需要在wp_head的hook中调用。
// 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');
关于php - WordPress PHP功能文件中的Google Analytics(分析)代码404错误跟踪,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24347522/