WordPress前后台页面新增全局新标签形式跳转页面
风铃白木
WordPress后台 👉🏿 外观 👉🏿 主题文件编辑器 👉🏿 找到❤️ functions.php ❤️,在最后添加以下代码,保存即可!
/**
* 让所有外链在新标签页打开(可选:也处理内链)
* 放到主题的 functions.php 或自定义插件里即可
*/
add_filter( 'wp_loaded', function () {
/*
* 优先级 99:尽量在其他插件/主题输出之后再处理,
* 防止被它们二次覆盖。
*/
ob_start( function ( $html ) {
/*
* 正则说明:
* - 匹配 <a ... href="..." ...>
* - 负向预查:跳过已带 target="_blank" 的链接
* - 捕获已有属性,防止重复添加
*/
$pattern = '#<a(?:[^>]+?href=["\']([^"\']*)["\'][^>]*)>#is';
$html = preg_replace_callback(
$pattern,
function ( $matches ) {
$tag = $matches[0];
// 已经带 target="_blank" 就跳过
if ( stripos( $tag, 'target="_blank"' ) !== false ) {
return $tag;
}
// 获取 href
$href = $matches[1];
// 如果想“仅外链”才新标签,取消下面三行注释
// $home = parse_url( home_url(), PHP_URL_HOST );
// $link = parse_url( $href, PHP_URL_HOST );
// if ( ! $link || $link === $home ) return $tag;
// 追加 target 及安全属性
$tag = preg_replace(
'#(<a\b[^>]*?)>#is',
'$1 target="_blank" rel="noopener noreferrer">',
$tag
);
return $tag;
},
$html
);
return $html;
} );
}, 99 );
评论(0)
暂无评论