# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: content, links, external, nofollow
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/external-links-new-tab/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Open External Links in a New Tab" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
