WordPress 所有外链在新标签打开

将下面的代码添加到主题的 function.php 中

function rt_add_link_target( $content ){
// use the <a> tag to split into segments
$bits = explode( '<a ', $content );
// loop though the segments
foreach( $bits as $key=>$bit ){
// fix the target="_blank" bug after the link
if ( strpos( $bit, 'href' ) === false ) continue;
// find the end of each link
$pos = strpos( $bit, '>' );
// check if there is an end (only fails with malformed markup)
if( $pos !== false ){
// get a string with just the link's attibutes
$part = substr( $bit, 0, $pos );
// for comparison, get the current site/network url
$siteurl = network_site_url();
// if the site url is in the attributes, assume it's in the href and skip, also if a target is present
if( strpos( $part, $siteurl ) === false && strpos( $part, 'target=' ) === false ){
// add the target attribute
$bits[$key] = 'target="_blank" ' . $bits[$key];
}
}
}
// re-assemble the content, and return it
return implode( '<a ', $bits );
}

 

Leave a Reply

登录后才能评论

💖 帮助我们更好的生产内容,请将本站加入广告屏蔽插件的白名单,非常感谢。
🚀 请尽快激活您的账号,账号注册未激活30天后将被清理。(已激活用户请忽略)
点击登录,重新获取激活邮件。