The following code in function.php, works fine for making the links – clickable,
add_filter( 'the_content', 'make_clickable', 12 );
But can I make the links to open in new tab?
The following code in function.php, works fine for making the links – clickable,
add_filter( 'the_content', 'make_clickable', 12 );
But can I make the links to open in new tab?
I am not sure if there’s a native function for this, but a little regex might help the case:
function open_links_in_new_tab($content){
$pattern = '/<a(.*?)?href=[\'"]?[\'"]?(.*?)?>/i';
$content = preg_replace_callback($pattern, function($m){
$tpl = array_shift($m);
$hrf = isset($m[1]) ? $m[1] : null;
if ( preg_match('/target=[\'"]?(.*?)[\'"]?/i', $tpl) ) {
return $tpl;
}
if ( trim($hrf) && 0 === strpos($hrf, '#') ) {
return $tpl; // anchor links
}
return preg_replace_callback('/href=http://wordpress.stackexchange.com/i', function($m2){
return sprintf('target="_blank" %s', array_shift($m2));
}, $tpl);
}, $content);
return $content;
}
add_filter('the_content', 'open_links_in_new_tab', 999);
The patterns might need a little improvements. Hope that helps!