Home » WordPress

WordPress 统计代码插件化

11 03月 2010 Views: No Comment Tags:

转自芒果

WordPress 添加统计代码通常采用在 footer.php 文件直接嵌入的方式。一旦主题更换,就需要重新插入统计代码,比较麻烦。

以芒果使用的 Google Analytics 为例,可以将其以插件的形式嵌入源代码,从而避免修改模板文件。

首先,将以下代码保存为 google-analytics.php

<?php
/*
Plugin Name: Google Analytics
Plugin URI: http://www.mangguo.org/
Description: This plugin allows you to add google analytics Tracking code to your page.
Author: Mangguo
Version: 1.0
Author URI: http://www.mangguo.org/
*/
add_action('wp_footer', 'google_analytics_code');
function google_analytics_code()
{
 include('google-analytics.txt');
}
?>

在上述代码中,通过 add_action 函数在页面底部引入 Google Analytics 插件。注释部分是插件信息,可以根据需要修改。当然,将 add_action 函数中的 wp_footer 替换为 wp_head 即可实现在页面头部引用统计代码,但会拖慢页面加载速度,一般不建议采用。

然后,将以下统计代码保存为 google-analytics.txt:

<!-- Google Analytics -->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-XXXXXX-X");
pageTracker._trackPageview();
</script>

其中,UA-XXXXXX-X 字符串为统计账号,需根据实际情况修改。

最后,将 google-analytics.php 和 google-analytics.txt 文件拷贝至 google-analytics 文件夹,并上传至插件目录,在 WordPress 插件管理面板激活启用即可。

原创文章如转载,请注明:转载自Xixis Blog [ http://www.xixis.net/ ]
本文链接地址:http://www.xixis.net/archives/statistics-code-of-wordpress-plugins.html

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.