我在我的网站上安装了W3 Total Cache插件,最近出现了这个错误:
您的活动主题:
·具有对的调用,但在关闭正文标签之前未直接调用
这是我的footer.php档案的结尾:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script') [0]; s.parentNode.insertBefore(ga, s);})();
</script>
<?php wp_footer(); ?>
</body>
</html>
正如您所看到的,wp_footer();
就在</body>
标记之前。我是不是错过了什么?
谢谢你的帮助。
我无意干扰"代码马"的答案,但仍然是:
wp_footer()是一个应该在上面的函数,Wordpress codex明确表示"将此模板标记放在主题模板(例如footer.php,index.php)中的标记之前"。
在我看来,正确的代码应该是这样的:
<?php wp_footer(); ?>
<script type="text/javascript">
Here goes your Google analytics code
</script>
</body>
</html>
所以,正如你所看到的。"wp_footer"位于Ganalytics代码之上,在这种情况下,不会出现任何问题。甚至还有一些小的WP插件专门用于插入谷歌分析,但它是为懒惰的人准备的,呵呵
你不应该在WordPress中直接调用<script>
标签。相反,使用wp_enqueue_script()
:
google-analytics.js
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script') [0]; s.parentNode.insertBefore(ga, s);})();
然后,在主题的functions.php
文件或插件文件中:
add_action( 'wp_enqueue_scripts', 'so20272587_add_analytics' );
function so20272587_add_analytics() {
$handle = 'google-analytics';
$src = 'path/to/google-analytics.js'; // where your JS file lives
$deps = array(); // add any dependencies' handles in here
$ver = false; // you can leave this false, or define your own version #
$in_footer = true; // if you want to load it in the footer
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
}
然后,您的Google Analytics脚本将作为网站页脚的一部分加载。