WordPress文章外部链接清除方法分享,有时候我们采集或者引用了其他文章,有时候会忘记去除外部链接或者是采集规则因为各种未知原因未处理干净a标签,我们就可以用如果方法对WordPress文章的外部链接进行清除。
操作流程
- 首先,备份了数据库,以防止意外情况发生。
- 登录到你的WordPress后台。
- 在左侧的导航菜单中,找到并点击“外观”选项,然后选择“编辑主题”子菜单。
- 在编辑主题文件的页面,找到并点击“functions.php”文件。
- 在functions.php文件的末尾添加以下代码:
- 将代码中的www.linfengnet.com改为自己的域名
- 注意在域名中的.符号前面加一个 英文的\符号。
- 添加完之后等一会你再看就会发现文章中的外部链接就被清除了。
推荐你使用WPCode 代码片段插件,你可以直接将下述代码添加为一个新的代码片段开启,关于这个插件的介绍推荐你看我之前文章:WordPress代码片段插件 WPCode。
清除全部文章外部链接代码
如果文章数量少,可以直接使用下面这个代码,会清除所有文章的外部链接。
// 注意备份数据库哦!!!
function remove_external_links() {
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$content = get_the_content();
$updated_content = preg_replace('/<a.*?href=["\'](http[s]?:\/\/(?!www\.linfengnet\.com)[^"\']*)["\'].*?>(.*?)<\/a>/i', '$2', $content);
if ($content !== $updated_content) {
$post_id = get_the_ID();
$post_data = array(
'ID' => $post_id,
'post_content' => $updated_content,
);
wp_update_post($post_data);
}
}
}
wp_reset_postdata();
}
add_action('init', 'remove_external_links');
根据搜索内容清除外部链接代码
如果在我们文章数量非常多的情况下,使用上面清除全部文章的代码,可能会导致占用服务器性能比较多,网站卡顿等情况,我们可以通过搜索的方式,搜索要清除的外部链接。
比如你的文章中存在www.baidu.com的外链,你就把www.baidu.com替换your_search_query,然后程序会搜索到存在www.baidu.com的文章,然后把它们存在的所有外部链接都去除。不单单是链接,你搜索其他特定关键词去清除也是可以的。
和上面清除全部文章中的代码一样,记得把remove_external_links函数里面的正则域名替换为自己的(这样就除了自己域名以外的链接都清空)。
$args = array(
's' => 'your_search_query', // 替换为你的搜索关键字
'post_type' => 'post',
'posts_per_page' => -1,
'fields' => 'ids', // 只获取文章ID
);
$query = new WP_Query($args);
$external_Links = array();
if ($query->have_posts()) {
$post_ids = $query->posts;
wp_reset_postdata();
// 将得到的id加入数组
$external_Links = $post_ids;
echo '文章ID已保存到数组中。';
} else {
echo '没有找到匹配的文章。';
}
function remove_external_links() {
global $external_Links;
foreach ($external_Links as $post_id) {
$post = get_post($post_id);
$content = $post->post_content;
$updated_content = preg_replace('/<a.*?href=["\'](http[s]?:\/\/(?!www\.linfengnet\.com)[^"\']*)["\'].*?>(.*?)<\/a>/i', '$2', $content);
if ($content !== $updated_content) {
$post_data = array(
'ID' => $post_id,
'post_content' => $updated_content,
);
wp_update_post($post_data);
}
}
}
add_action('init', 'remove_external_links');
使用之后
上面代码使用完之后,请将它们从你的functions.php文件中删除或者是从WPCode插件中关闭即可。
仅清除失效链接
如果是仅需要清除失效链接,那么推荐你使用之前的我们分享的Broken Link Checker插件,详情请你看:WordPress文章失效图片/链接检测插件推荐:Broken Link Checker。