I want to modify all current links to Amazon on my site, to add a rel="nofollower"
tag — they currently have an existing rel="noopener"
tag which, as I thought, was always placed at the beginning: <a rel="noopener" href="https://amzn.to/example">text</a>
I went into functions.php and added the following:
// add nofollow to Amazon
function add_noFollow($text) {
$text = str_replace('rel="noopener" href="https://amzn.to', 'rel="noopener nofollow" href="https://amzn.to', $text);
return $text;
}
add_filter('the_content', 'add_noFollow');
This worked as expected, keeping the full url (e.g. https://amaz.to/example)
. But then I realized that, for some reason, some links on my site were originally structured like this:
<a href="https://amzn.to/example" target="_blank" rel="noopener">text</a>
Since some links contained the rel="noopener"
at the end, it means that I will have to modify the entire <a>
tag, keeping the original url.
How can I modify my existing function to first detect if the <a>
tag contains amzn.to
and then replace the entire thing (adding the desired parameters, e.g. rel="nofollower noopener"
) but keeping the original url?
I thought some sort of wilcard function is needed, but I lack the necessary knowledge to go about it.