Skip to content

Instantly share code, notes, and snippets.

@tommusrhodus
Created November 4, 2023 20:40
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 tommusrhodus/d464aec87994394acecd6bf7f6ffd1ad to your computer and use it in GitHub Desktop.
Save tommusrhodus/d464aec87994394acecd6bf7f6ffd1ad to your computer and use it in GitHub Desktop.
Converting external links to open in a new window automagically.
<?php
/**
* Filters given content to add target="_blank" to external links.
*
* @see https://developer.wordpress.org/reference/files/wp-includes/html-api/class-wp-html-tag-processor.php/
* @see https://adamadam.blog/2023/02/16/how-to-modify-html-in-a-php-wordpress-plugin-using-the-new-tag-processor-api/
* @param string $content Content of the post.
* @return string
*/
function prefix_external_link_target_blank( $content ): string {
// Instantiate the processor.
$processor = new WP_HTML_Tag_Processor( $content );
// Get the domain of the site without scheme.
$site_domain = wp_parse_url( site_url(), PHP_URL_HOST );
// Loop through all the A tags and parse href to see if it's an external link.
while ( $processor->next_tag( 'A' ) ) {
$href = $processor->get_attribute( 'href' );
$root_domain = wp_parse_url( $href, PHP_URL_HOST );
// If root domain is null, it's an internal link (no host), skip.
if ( null === $root_domain ) {
continue;
}
// If the root domain is not the same as the site domain, it's an external link.
if ( $root_domain !== $site_domain ) {
$processor->set_attribute( 'target', '_blank' );
$processor->set_attribute( 'rel', 'nofollow external noopener noreferrer' );
}
}
return $processor->get_updated_html();
}
add_filter( 'the_content', 'prefix_external_link_target_blank', 999 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment