How can I modify all existing <a> tags while keeping the urls themselves?
-
20-04-2021 - |
Question
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.
Solution
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(
'/<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
function($m) {
if (strpos($m[1], "amzn.to") !== false)
return '<a href="'.$m[1].'" rel="nofollow noopener" target="_blank">'.$m[2].'</a>';
else
return '<a href="'.$m[1].'" rel="noopener" target="_blank">'.$m[2].'</a>';
},
$content);
return $content;
}
add_filter('the_content', 'add_nofollow_content');