# Add nofollow to External Links in Content

> Adds rel="nofollow" to links in posts and pages that point to other websites, while keeping any rel values already set. Links to your own domain are untouched.

- Type: PHP
- Runs: Frontend only
- Category: [SEO](https://wpide.com/library/category/seo/)
- Tags: nofollow, links, external
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/nofollow-external-links/

## Code

```php
// Domains whose links stay followed (your own domain is always followed).
$wpide_follow_domains = array( 'wordpress.org' );

add_filter( 'the_content', function ( $content ) use ( $wpide_follow_domains ) {
    if ( false === stripos( $content, '<a ' ) ) {
        return $content;
    }

    $own = wp_parse_url( home_url(), PHP_URL_HOST );

    $result = preg_replace_callback( '/<a\s[^>]*>/i', function ( $m ) use ( $own, $wpide_follow_domains ) {
        $tag = $m[0];

        if ( ! preg_match( '/href=["\'](https?:)?\/\/([^\/"\':?#]+)/i', $tag, $href ) ) {
            return $tag;
        }

        $host = strtolower( $href[2] );

        foreach ( array_merge( array( $own ), $wpide_follow_domains ) as $domain ) {
            $domain = strtolower( (string) $domain );

            if ( $host === $domain || substr( $host, -strlen( '.' . $domain ) ) === '.' . $domain ) {
                return $tag;
            }
        }

        if ( preg_match( '/\srel=(["\'])([^"\']*)\1/i', $tag, $rel ) ) {
            if ( preg_match( '/\bnofollow\b/i', $rel[2] ) ) {
                return $tag;
            }

            return str_replace( $rel[0], ' rel="' . esc_attr( trim( $rel[2] . ' nofollow' ) ) . '"', $tag );
        }

        return substr( $tag, 0, -1 ) . ' rel="nofollow">';
    }, $content );

    return null === $result ? $content : $result;
}, 20 );
```

## Notes

Add domains you trust to $wpide_follow_domains to keep their links followed.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add nofollow to External Links in Content" 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/
