I have some cloaking affiliate links to which I would like to add the attributes of nofollow.

However, I'm looking for a way in coding that will allow me to target links that contain specific string, like /go/brand.

While searching, I found this code somewhere, but it didn't work for me in functions.php, so I was hoping someone might provide me with something that may do the job for me.

Thank you so much in advance!

add_filter( 'the_content', 'my_string_replacements');
function my_string_replacements ( $content ) {
    if ( ! is_admin() && is_main_query() ) {
        return preg_replace('/<a(.*href=".*\/go\/pluto\/?".*)>/', '<a$1 rel="nofollow">', $content );
    return $content;

The replace code is replacing the whole a element content with <a rel="nofollow">. Here's the correction:

I used (.+?) between <a and href" and before and after /go/pluto/ to the closing >. Then in the replace, we put $1 $2 $3 etc. to keep them and add rel="nofollow". You can check in this test, and here's explanation about the replace.

return preg_replace('/<a(.+?)href="(.+?)\/go\/pluto\/(.+?)"(.+?)>/', '<a$1href="$2/go/pluto/$3" rel="nofollow"$4>', $content );


Considering there are links that contains rel attribute already, we will run regex that searches for links that does have rel but doesn't contain nofollow and add nofollow:

return preg_replace('/<a(.+?)href="(.+?)\/go\/pluto\/(.+?)"(.+?)rel="((?!nofollow).)*(?=")/', '$0 nofollow', $content);

I'm still figuring out the appropriate code to insert rel if the a element doesn't contain it.

  • Thank you very much for your suggestion, it partially worked, it added the nofollow for some links and for some others it didnt. The link that it didn't work with had already some attributes like rel="noopener noreferrer" – marouane91 Dec 14 '19 at 20:40
  • I updated the answer with regex code to add nofollow to existing rel – Heba Fareed Dec 16 '19 at 7:25
  • Thank you so much mate, you saved me :) I appreciate your followup mate, the following one worked for me and this has done the job for me: return preg_replace('/<a(.+?)href="(.+?)\/go\/(.+?)"(.+?)>/', '<a$1href="$2/go/$3" rel="nofollow"$4>', $content ); – marouane91 Dec 16 '19 at 11:31
  • You are welcome anytime buddy :) please approve and vote up the answer. – Heba Fareed Dec 16 '19 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.