将WordPress的文章/评论/访客外链接转为内链,支持加密和新窗口跳转

用WordPress好几年了,一直没处理文章内容、评论内容和访客外部链接的跳转问题。最近看很多MJJ博客都搞了,我也跟风搞了个,现在大多数外链都转换为内链接,并使用base64加密,代码是抄袭别人的,挺好用。

一、先用正则以及wp的钩子修改外链形式为 /go/xxxxx
二、然后解密xxxx部分,用template_redirect钩子和wp_redirect函数进行302跳转

代码下载:https://file.lingchenzi.com/web/2019/go.zip


//文章正文、评论内容和访客的外部链接转换为内链,并使用base64加密跳转
function convert_to_internal_links($content){
preg_match_all('/\shref=(\'|\")(http[^\'\"#]*?)(\'|\")([\s]?)/',$content,$matches);
if($matches){
foreach($matches[2] as $val){
if(strpos($val,home_url())===false){
$rep = $matches[1][0].$val.$matches[3][0];
$new = '"'.home_url().'/go/'.base64_encode($val).'" target="_blank"';
$content = str_replace("$rep","$new",$content);
}
}
}
return $content;
}
add_filter('the_content','convert_to_internal_links',99); // 文章正文外链转换
add_filter('comment_text','convert_to_internal_links',99); // 评论内容的链接转换
add_filter('get_comment_author_link','convert_to_internal_links',99); // 访客的链接转换

function inlo_redirect() {
$baseurl = 'go';
$request = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //如果启用了https,请将http改为https
$hop_base = trailingslashit(trailingslashit(home_url()).$baseurl); //删除末尾的 斜杠/ 符号
if (substr($request,0,strlen($hop_base)) != $hop_base) return false;
$hop_key = str_ireplace($hop_base, '', $request);
if(substr($hop_key, -1) == '/')$hop_key = substr($hop_key, 0, -1);
if (!empty($hop_key)) {
$url = base64_decode($hop_key);
wp_redirect( $url, 302 );
exit;
}
}
add_action('template_redirect','inlo_redirect');

代码放functions.php函数文件

修改一下robots.txt,添加 Disallow: /go/,禁止搜索引擎收录

转自:http://www.inlojv.com/4750.html

将WordPress的文章/评论/访客外链接转为内链,支持加密和新窗口跳转》有6个想法

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注