我不确定是否有用于此的本机函数,但一点正则表达式可能会有所帮助:
function open_links_in_new_tab($content){
$pattern = \'/<a(.*?)?href=[\\\'"]?[\\\'"]?(.*?)?>/i\';
$content = preg_replace_callback($pattern, function($m){
$tpl = array_shift($m);
$hrf = isset($m[1]) ? $m[1] : null;
if ( preg_match(\'/target=[\\\'"]?(.*?)[\\\'"]?/i\', $tpl) ) {
return $tpl;
}
if ( trim($hrf) && 0 === strpos($hrf, \'#\') ) {
return $tpl; // anchor links
}
return preg_replace_callback(\'/href=/i\', function($m2){
return sprintf(\'target="_blank" %s\', array_shift($m2));
}, $tpl);
}, $content);
return $content;
}
add_filter(\'the_content\', \'open_links_in_new_tab\', 999);
这些模式可能需要一些改进。希望有帮助!