Created
April 1, 2015 14:08
-
-
Save roytanck/7f0392386914aa2adfb2 to your computer and use it in GitHub Desktop.
Open external links inside WordPress comments in a new tab/window
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ){ | |
// 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 ); | |
} | |
add_filter( 'comment_text', 'rt_add_link_target' ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Love the gist. One thing I noticed is that when it runs through the first bit, it will add an errant target="_blank", so I added
if ( strpos( $bit, 'href' ) === false ) continue;
after the foreach opening and that seems to fix it!