How to add no-follow attribute for certain external link

Exactly! would you like to add nofollow attribute to a certain external link or domain address. Here is the solution I got for my client's site.

The purpose was to add nofollow attribute to affiliate links so that Google index nofollowed to all affiliate links for certain domain URL. Below is the code snippet to add your theme's functions.php file.

//* Add no-follow attribute for certain external link
function add_nofollow( $content ) {

    $my_xurl = "https://www.example.com";
    preg_match_all( '~<a.*>~isU', $content, $uri_match );

    for ( $i = 0; $i <= sizeof( $uri_match[0] ); $i ++ ) {
        if ( isset( $uri_match[0][ $i ] ) && ! preg_match( '~nofollow~is', $uri_match[0][ $i ] )
             && ( preg_match( '~' . preg_quote( $my_xurl ) . '~', $uri_match[0][ $i ] ))
            ) {
            $uri_change = trim( $uri_match[0][ $i ], ">" );
            $uri_change .= ' rel="nofollow">';
            $content = str_replace( $uri_match[0][ $i ], $uri_change, $content );
        }
    }

    return $content;
}

add_filter( 'the_content', 'add_nofollow' ); 


Now, you have to change or replace the URL of https://www.example.com with your targeted URL so that our function work for the URL.

If you are unable or face any issue don't forget to comment below. Thanks :)

Read More: WordPress: Remove Query Strings From Static Resources

Millennial & an introvert. Totally dashing beyond Passion. Code is poetry that never lies. Facebook or Drop Mail

0 comments: