Last active
November 16, 2018 12:55
-
-
Save Xyborg/5c20a4bef9b6e9bca19ca2573efb5bfe to your computer and use it in GitHub Desktop.
Open WordPress content links on a new tab (target="_blank")
This file contains 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
/* The following WordPress function will look for links INSIDE the post contents */ | |
/* and add the target="_blank" to each one so they will open in a new tab */ | |
function xbg_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=/i', function($m2){ | |
return sprintf('target="_blank" %s', array_shift($m2)); | |
}, $tpl); | |
}, $content); | |
return $content; | |
} | |
add_filter('the_content', 'xbg_links_in_new_tab', 999); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment