先告诉大家这个是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 条评论
哈哈搞了半天还是不行哦
不好意思,你评论的任何链接我只能手动编辑了
没事,我就是测试哈,因为做的东西要用到这个功能,网上搜索到你这了,就试试,发现没有完美的方案。只有特定的几种形式才可以。
行,我只能将其定义为过滤词了
有点迷糊。
建议写点z-blog的,我会感激死你的。
奖励下,点广告咯
是否支持中文?
http://www.测试.com http://www.测试.美国 http://www.测试.日本 试试就知道啦