Home / Archive / Open External Links in a New Tab
Duplicate Snippet

Embed Snippet on Your Site

Open External Links in a New Tab

Automatically open all external links added in posts in a new tab.

300+
Code Preview
php
<?php
add_filter( 'the_content', function ( $content ) {
	// This snippet requires the DOMDocument class to be available.
	if ( ! class_exists( 'DOMDocument' ) ) {
		return $content;
	}
	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;
} );

Comments

Add a Comment