Created
September 22, 2020 16:09
-
-
Save kmwalsh/6e0308533f09832279addc8496636022 to your computer and use it in GitHub Desktop.
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
/** | |
* | |
* All internal links should open in a new window with rel=noopener | |
* | |
*/ | |
if ( ! function_exists( 'force_external_links' ) ) { | |
add_filter('the_content', 'force_external_links'); | |
add_filter('acf_the_content', 'force_external_links'); | |
function force_external_links($content) { | |
return preg_replace_callback('/<a[^>]+/', 'force_external_links_callback', $content); | |
} | |
function force_external_links_callback($matches) { | |
$link = $matches[0]; | |
$parsed_site_link = parse_url(get_bloginfo('url')); | |
$site_host = $parsed_site_link['host']; | |
// is our domain in the host or is the scheme empty (anchor link, truncated link) | |
if ( strpos($link, $site_host ) === false && strpos( $link, 'http' ) !== false ) { | |
$link = preg_replace("%(href=\S(?!$site_host))%i", 'target="_blank" $1', $link); | |
// is noopener in the rel attribute | |
if ( strpos($link, 'noopener' ) === false) { | |
$link = preg_replace("%(href=\S(?!$site_host))%i", 'rel="noopener" $1', $link); | |
} | |
} | |
return $link; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note - breaks rel=noreferrer links