0

我在我的站点中安装了 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>标签之前。我错过了什么吗?

谢谢您的帮助。

4

2 回答 2

0

您不应该<script>直接在 WordPress 中调用标签。相反,使用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(分析)脚本将作为您网站页脚的一部分加载。

于 2013-11-28T22:41:12.867 回答
0

我并不是要干涉“codehorse”的回答,但仍然:

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 插件,但它是为懒人准备的,呵呵

于 2013-11-28T18:33:50.713 回答