Last active
January 30, 2024 14:45
-
-
Save knolaust/bb499265b7a02050a9359c50fcc89166 to your computer and use it in GitHub Desktop.
Open External Links in WordPress Content Blocks or Editors in a New Tab
This file contains hidden or 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
<?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; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment