修复博客bug,代码高亮的链接自动添加了nofollow问题

提醒:本文最后更新于 2653 天前,文中所描述的信息可能已发生改变,请仔细核实。

在《无事瞎说几句,顺便说下几个问题》中的#6楼,我提到了


现在解决了,原代码是

add_filter('the_content','the_content_nofollow',999);
function the_content_nofollow($content){
preg_match_all('/href="(.*?)"/',$content,$matches);
if($matches){
    foreach($matches[1] as $val){
        if( strpos($val,home_url())===false ) $content=str_replace("href=\"$val\"", "href=\"$val\" rel=\"external nofollow\" ",$content);
    }
}
return $content;
}

修改为:

add_filter('the_content','the_content_nofollow',999);
function the_content_nofollow($content){
preg_match_all('/href="(.*?)"/',$content,$matches);
if($matches){
    foreach($matches[1] as $val){
        if( strpos($val,home_url())===false ) $content=str_replace("<a href=\"$val\"", "<a href=\"$val\" rel=\"external nofollow\" ",$content);
    }
}
return $content;
}

就好了。。。坑爹啊。。。

不过更推荐小天转的js源码,源码如下:

<script type="text/javascript">
function externallinks()
{
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++)
{
var anchor = anchors[i];
if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external nofollow")
{
anchor.target = "_blank";
}
}
}
window.onload = externallinks;
</script>

以上这段代码,放在footer.php就可以用,他会对external nofollow标签添加_blank新窗口打开链接的模式。(functions.php那个就省了)

注,我放在footer.php的下面源码之前:

<?php wp_footer(); ?>
</body>
</html>

footer.php的后处理就是好啊。。。预先处理果然有些弊端。。。

转载请注明转自:kn007的个人博客的《修复博客bug,代码高亮的链接自动添加了nofollow问题