一般来说,为了防止本站流量和权重的流失,需要给站内链接添加 nofollow
属性。
但是如果每次都手动添加会很麻烦。我之前写过关于一篇用 JavaScript 批量添加 nofollow
的文章:
Z-Blog给文章所有的站外a链接添加nofollow的方法 不过搜索引擎可能会不认 JS 代码。
今天有时间,又重新改造了一下,用 PHP 批量给文章中的站外链接 添加 nofollow
属性。
找到 /zb_system/function/c_system_event.php
文件,找到 $article = $articles[0];
代码,大约在1145行(当然您也可以放在其他合适的位置)。
在下面添加以下代码:
/* a 链接添加 nofollow */
$domain = $zbp->option['ZC_BLOG_HOST']; //获取网站域名
$log_content = $article->Content; //文章内容
/* 正则替换所有 a 链接 */
preg_match_all('/href="(.*?)"/', $log_content, $matches);
if ($matches) {
foreach ($matches[1] as $val) {
if (strpos($val, $domain) === false) {
$log_content = str_replace('href="' . $val . '"', 'href="' . $val . '" rel="external nofollow" ', $log_content);
}
}
}
$article->Content = $log_content;
网上有资料显示,把图片的链接也给替换了,博主试了下,好像没什么效果。如果您需要,可以在倒数第二行添加如下代码:
preg_match_all('/src="(.*?)"/', $log_content, $matches);
if ($matches) {
foreach ($matches[1] as $val) {
if (strpos($val, $domain) === false) {
$log_content = str_replace('src="' . $val . '"', 'src="' . $val . '" rel="external nofollow" ', $log_content);
}
}
}
注意:没有代码基础的请做好备份,以免造成网站无法显示等问题。
$zbp->option['ZC_BLOG_HOST']
Z-Blog的网站域名
$article->Content;
Z-Blog的文章内容
简化一下:
/* a 链接添加 nofollow */
preg_match_all('/href="(.*?)"/', $article->Content, $matches); //正则替换所有 a 链接
if ($matches) {
foreach ($matches[1] as $val) {
if (strpos($val, $zbp->option['ZC_BLOG_HOST']) === false) {
$article->Content = str_replace('href="' . $val . '"', 'href="' . $val . '" rel="external nofollow" ', $article->Content);
}
}
}
这样就大功告成了,我们可以使用这个插件,自动标注带有 nofollow 的标签:Chrome插件:(NoFollow)自动标出带有nofollow的a链接
声明:本文由w3h5原创,转载请注明出处:《利用PHP给Z-Blog文章内的所有站外a链接添加nofollow》 https://cloud.tencent.com/developer/article/1538004