Open External Links in a New Tab
Adds target="_blank" and rel="noopener noreferrer" to links in post content that point to other domains. Optionally adds nofollow too. Requires WordPress 6.2 or newer.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
$add_nofollow = false; // Set to true to also add rel="nofollow".
if ( ! class_exists( 'WP_HTML_Tag_Processor' ) || false === stripos( $content, '<a ' ) ) {
return $content;
}
$site_host = wp_parse_url( home_url(), PHP_URL_HOST );
$tags = new WP_HTML_Tag_Processor( $content );
while ( $tags->next_tag( 'a' ) ) {
$href = $tags->get_attribute( 'href' );
if ( ! is_string( $href ) || ! preg_match( '#^https?://#i', $href ) ) {
continue;
}
$host = wp_parse_url( $href, PHP_URL_HOST );
if ( ! $host || strtolower( $host ) === strtolower( (string) $site_host ) ) {
continue;
}
$rel = $tags->get_attribute( 'rel' );
$parts = is_string( $rel ) ? preg_split( '/\s+/', trim( $rel ) ) : array();
$parts = array_merge( array_filter( $parts ), array( 'noopener', 'noreferrer' ) );
if ( $add_nofollow ) {
$parts[] = 'nofollow';
}
$tags->set_attribute( 'target', '_blank' );
$tags->set_attribute( 'rel', implode( ' ', array_unique( $parts ) ) );
}
return $tags->get_updated_html();
}, 20 );
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.