Skip to content

Instantly share code, notes, and snippets.

@kmwalsh
Created September 22, 2020 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmwalsh/6e0308533f09832279addc8496636022 to your computer and use it in GitHub Desktop.
Save kmwalsh/6e0308533f09832279addc8496636022 to your computer and use it in GitHub Desktop.
/**
*
* 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;
}
}
@kmwalsh
Copy link
Author

kmwalsh commented Oct 8, 2020

Note - breaks rel=noreferrer links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment