最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to add no follow to specific links?

programmeradmin3浏览0评论

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;
}

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;
}
Share Improve this question edited Dec 14, 2019 at 12:48 butlerblog 5,1213 gold badges28 silver badges44 bronze badges asked Dec 14, 2019 at 6:27 marouane91marouane91 176 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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 );

Edit:

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.

发布评论

评论列表(0)

  1. 暂无评论