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 );
}
(0)

相关推荐