《Google Analytics之出站链接跟踪》中已经介绍了如何通过事件跟踪的方式来记录出站链接点击的方法,但是对于文章中的出站链接如果每个都手工加入onClick属性是多么蛋疼的事情
本文就介绍一个插件,其实也不能算插件了,就一个正则替换而已,通过这个插件会自动为文章中的出站链接加上事件跟踪
你可以在你的plugin目录新新建一个文件,贴入对应的代码,或者直接在本文底部下载插件包,解压到wp-content/plugins目录
由于插件实在太简陋,或者说我其实还不怎么会做WordPress插件,所以木有后台配置界面,几个地方需要自己修改下代码才能使用,好蛋疼的插件。。。。
以后有时间、有必要的话,我会学习下wordpress插件制作,加入后台设置功能
跟踪出站域名代码
如果你不想知道用户点击的出站链接URL,只想看到到了哪个域名,请使用此代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19< ?php
/*
Plugin Name: Add Post TrackEvent
Plugin URI: http://xfeng.me/add-post-trackevent-wordpress-plugin/
Description: This plugin automatically add the onclick="_gaq.push(['_trackEvent', 'category', 'action', 'URL']);" to link in a post. You can modify category
Author: JoysBoy
Author URI: http://xfeng.me
Version: 0.1
Put in /wp-content/plugins/ of your Wordpress installation
*/
add_filter('the_content', 'add_post_trackevent_replace');
function add_post_trackevent_replace ($content)
{ global $post;
$pattern = "/[(.*?)< \/a>/i";
$replacement = '<a $1href=$2$3$4/$5$7 onclick="_gaq.push([\'_trackEvent\', \'OutboundLink\', \'Goto inPost Link\' \'$4\']);" $8>$9]((\)';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
?>
跟踪出站URL代码
如果你想知道用户点击出站链接的具体URL,那么请使用下面代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19< ?php
/*
Plugin Name: Add Post TrackEvent
Plugin URI: http://xfeng.me/add-post-trackevent-wordpress-plugin/
Description: This plugin automatically add the onclick="_gaq.push(['_trackEvent', 'category', 'action', 'URL']);" to link in a post. You can modify category
Author: JoysBoy
Author URI: http://xfeng.me
Version: 0.1
Put in /wp-content/plugins/ of your Wordpress installation
*/
add_filter('the_content', 'add_post_trackevent_replace');
function add_post_trackevent_replace ($content)
{ global $post;
$pattern = "/[(.*?)< \/a>/i";
$replacement = '<a $1href=$2$3$4$6 onclick="_gaq.push([\'_trackEvent\', \'OutboundLink\', \'Goto inPost Link\' \'$4\']);" $7>$8]((\)';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
?>
Tips
这里你需要修改一个地方,把xfeng修改为你的域名,用途是过滤掉本站自己的链接
如果你的域名是abc.com,你可以直接把xfeng替换为abc即可,如果你的域名是blog.abc.com,你把xfeng替换为blog.abc就行
插件下载
GitHub下载:http://s.xfeng.me/y7ajHG
如果使用该插件导致文章不能正常输出,请禁用插件,并向我反馈具体报错信息,我会尽快修复问题
后面有空学习下怎么制作插件后台配置页面,实现页面配置跟踪方案、自动获取博客域名、自定义修改事件跟踪category、action名