Wordpress php功能打开所有出站链接的新选项卡


Wordpress php function to open all outbound links in new tab

谁想要一个虚拟的热巧克力饼干?

我正在寻找一个Wordpress php函数打开所有出站链接在新的选项卡。

我发现了几个类似于下面的功能解决方案,但它们只适用于帖子/页面,而不适用于硬编码到主题中的项目(如社交媒体按钮):

/* OPEN ALL OUTBOUND LINKS IN NEW TAB */
function autoblank($text) {
$return = str_replace('href=', 'target="_blank" href=', $text);
$return = str_replace('target="_blank"
href="http://csihealth.lenadev.com',
'href="http://csihealth.lenadev.com', $return);
$return = str_replace('target="_blank" href="#', 'href="#', $return);
$return = str_replace(' target = "_blank">', '>', $return);
return $return;
}
add_filter('the_content', 'autoblank');
add_filter('comment_text', 'autoblank');

是否有办法改变这一点,使其适用于所有出站链接?不只是帖子/页面?

你可以用jQuery:

$(function() {
    $( 'a[href^="//"],a[href^="http"]' )
    .not( '[href*="' + window.location.hostname + '"]' )
    .attr('target', '_blank');
});

这将找到任何不是相对链接的链接(因此,任何可能是出站的链接),然后删除那些实际上指向您自己的网站的链接,并将剩下的目标设置为空白。