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

猜你喜欢:

点赞
  1. 皮皮说道:

    这个修改简单,赞!

  2. 荣耀博客说道:

    博主你这个 代码高亮插件用的那个

    1. Bee.T说道:

      @荣耀博客 没用插件,prism.js。你你可以试下 https://www.tmioe.com/2019/pure-highlightjs-wordpress 这个插件。

  3. 心灵博客说道:

    看错了,外链看成链接了,

    1. Bee.T说道:

      @心灵博客 你终于有看错的时候了 :guai:

  4. 心灵博客说道:

    在模板头部价格base不好吗?页面html还没那么大

发表评论

电子邮件地址不会被公开。必填项已用 * 标注