Hey!
Just a point of clarification, what do you mean exactly by “so that I can manually add a no-follow tag”?
Might help me understand what you’re trying to do.
Thread Starter
amedic
(@amedic)
Hi,
what I meant is when I edit post and when I add no follow to the link.
That script is working, but it overwrites nofollow tag with “noopener noreferrer”.
What I would like is to edit this script, but if I add nofollow to the link from post edit, that it is not overwritten.
I’m hoping it is more understandable now what I’m trying to achieve.
Ahh I understand now! Thanks for that.
So, I tested out your code above, and I see what the issue is. I don’t have an answer going about it a PHP and WP filter way (all the preg_replace and editing the $content is complicated), but I have something using Javascript that I think can be adapted for your needs. It’s what I use on my own sites to append rel attributes to all external links, as well as adding an image (via adding a CSS class) to all external links. Original code is below and then code that should work for your needs is below that.
/* Add 'text-external' class and rel="external noopener noreferrer" to anchors that are external links
* (this.hostname !== location.hostname) but NOT to anchors containing images or subsequent parameters.
* Notice multiple parameters for .not() ~mj */
function addImageToExternalLinks() {
$("a").filter(function() {
if ($debug) {
console.log('Inside addImagetoExternalLinks()')
console.log('this.hostname: ' + this.hostname)
console.log('location.hostname: ' + location.hostname)
}
return this.hostname && this.hostname !== location.hostname;
}).not('a:has(img), a:has("span.icon")')
.attr("rel","external noopener noreferrer")
.attr("target", "_blank")
.addClass('text-external');
}; // end addImageToExternalLinks()
addImageToExternalLinks();
And code that should work for you:
function addImageToExternalLinks() {
$("a").filter(function() {
if ($debug) {
console.log('Inside addImagetoExternalLinks()')
console.log('this.hostname: ' + this.hostname)
console.log('location.hostname: ' + location.hostname)
}
return this.hostname && this.hostname !== location.hostname;
}).attr("rel","noopener noreferrer")
.attr("target", "_blank")
}; // end addImageToExternalLinks()
addImageToExternalLinks();
Your PHP is flawed, I’m surprised it works at all. The initial if statement should be:
if (strpos($externalLink, 'rel') === false)
In a quick test it works as expected, an existing rel="nofollow" remains unmolested.