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.


I solved the issue with help from this answer: https://wordpress.stackexchange.com/a/159570/176615

// add nofollow to Amazon
function add_nofollow_content($content) {
    $content = preg_replace_callback(
    function($m) {
        if (strpos($m[1], "amzn.to") !== false)
            return '<a href="'.$m[1].'" rel="nofollow noopener" target="_blank">'.$m[2].'</a>';
            return '<a href="'.$m[1].'" rel="noopener" target="_blank">'.$m[2].'</a>';
    return $content;
add_filter('the_content', 'add_nofollow_content');

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.