Open External Links in WordPress Content Blocks or Editors in a New Tab

01/30/2024
Back to Blogs
<?php
/**
 * Modify External Links to Open in New Tab.
 *
 * This code modifies external links within the post content to open in a new tab
 * and adds the "noopener noreferrer" attributes for security.
 *
 * Gist Keywords: wordpress, customization
 *
 * @category WordPress
 * @version  1.0.0
 * @author   Knol Aust
 */

add_filter( 'the_content', function ( $content ) {
	// Check if the DOMDocument class is available.
	if ( ! class_exists( 'DOMDocument' ) ) {
		return $content;
	}
	// Check if the current post is a single post in the main query loop.
	if ( ! is_single() || ! in_the_loop() || ! is_main_query() ) {
		return $content;
	}

	$dom          = new DOMDocument();
	$load_content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
	if ( empty( $load_content ) ) {
		return $content;
	}
	@$dom->loadHTML( $load_content );
	$links = $dom->getElementsByTagName( 'a' );

	foreach ( $links as $link ) {
		if ( strpos( $link->getAttribute( 'href' ), home_url() ) !== false ) {
			continue;
		}
		$old_link = $link->C14N();
		$link->setAttribute( 'target', '_blank' );
		$link->setAttribute( 'rel', 'noopener noreferrer' );

		$content = str_replace( $old_link, $link->C14N(), $content );
	}

	return $content;
} );