先告诉大家这个是WordPress原生的哦,不知道大家有没有注意到很多Spammer的评论里的网址什么的都会被WordPress自动转换成超链接,我之前为了迎合个人需求而将D&Z主题集成sem-autolink-uri这个插件的功能,但此后一直觉得不爽,因为总是有种非WordPress原装的正则表达式都是不完美的感觉,再是代码有些长.鉴于它会将评论中URL转换成超链接的功能,于是今天一早爬起来疯狂的搜索到底咋回事.后来发现\wp-includes\default-filters.php文件里一段代码如下:
/* 自动将评论内容中的URL转换为超链接 */
add_filter( 'comment_text', 'make_clickable',9);
add_filter( 'comment_text', 'make_clickable',9);
细想后,日志内的URL转换为超链接不就很简单么?就冲着这原生的玩意,朝着主题的function.php里边添加以下两段代码.(注意:如果URL夹在文字中间,那么在它前后各敲上一个空格吧,不然它就不工作了,这个是WordPress本身的小BUG.)
/* 自动将日志中的URL转换为超链接 */
add_filter( 'the_content', 'make_clickable');
add_filter( 'the_excerpt', 'make_clickable');
add_filter( 'the_content', 'make_clickable');
add_filter( 'the_excerpt', 'make_clickable');
测试一下我自己的博客的URL:
http://www.wancheng.li
瞧瞧,圆满成功.另外,虽然提高了阅读者的便携性,但是打开地址后是直接在本窗口跳转,所以不得不再次于以上代码之后增加几句简单的代码,详情如下:
add_filter( 'the_content', 'add_redirect_link');
add_filter( 'the_excerpt', 'add_redirect_link');
/* 重定向+新窗口打开 */
function add_redirect_link($text = ''){
$text=str_replace('href="', 'target=_blank href="'.get_option('home').'/?r=', $text);
$text=str_replace("href='", "target=_blank href='".get_option('home')."/?r=", $text);
return $text;
}
add_action('init', 'redirect_link');
function redirect_link(){
$redirect = $_GET['r'];
if($redirect){
if(strpos($_SERVER['HTTP_REFERER'],get_option('home')) !== false){
header("Location: $redirect");
exit;
}
else {
header("Location: http://wancheng.li/");
exit;
}
}
}
add_filter( 'the_excerpt', 'add_redirect_link');
/* 重定向+新窗口打开 */
function add_redirect_link($text = ''){
$text=str_replace('href="', 'target=_blank href="'.get_option('home').'/?r=', $text);
$text=str_replace("href='", "target=_blank href='".get_option('home')."/?r=", $text);
return $text;
}
add_action('init', 'redirect_link');
function redirect_link(){
$redirect = $_GET['r'];
if($redirect){
if(strpos($_SERVER['HTTP_REFERER'],get_option('home')) !== false){
header("Location: $redirect");
exit;
}
else {
header("Location: http://wancheng.li/");
exit;
}
}
}
- 转载请注明来源:凤凰不归巢 » 《自动将日志内的URL转为超链接》
- 本文链接地址:http://wancheng.li/1373.html

本文有 47 条评论
你的超链接阴影效果很好看 :toux:
CSS增加一句text-shadow:1px 1px 1px #999;你也值得拥有
IE不支持。。
确实不支持
不错的技术博客 学习了!
:han: 是我去你那学习…另外,我这是生活类博客哦.呵呵
这篇文章 都是代码 我是没看懂 哈哈~~~ , 不是技术博客吗?
生活为主,呵呵
话说,这样不就可以自动添加nofollow。。 , 晚上正在研究这事。。
可以的…再下面那重定向里边添加
:dx: 这个不错, 所有的连接都是本地走, 不过浪费php的资源来str_replace
我今天来是点广告来啦。
我都琢磨是否要在日志顶部换成GGAD
換吧,反正你也沒得獎
你的博客做得不错啊,我喜欢
大家喜欢才是真的喜欢 :wx:
虽然用不上 但也要有情支持一下
:wx: 谢谢支持
PJer只是表示路过!
最近都不写那个搞笑或者我看的懂的文章了?
混生来学习了,呵呵