I would like to add rel="nofollow" and target="_blank" for all external links in my Wordpress posts and pages permanently. I am aware, that there are plugins, which do the same, but as soon as they get disabled, all changes will be reversed and the articles are the same as from the beginning.
I do not know how to differ between internal or external links nor how to check if there is already a rel="nofollow" or target="_blank" attribute.
I guess the best way of doing this would be using PHP instead of MySQL. I already searched the web for guides, tutorials or plugins, without success.
May someone help me? I appreciate your support.
I have got a solution for applying nofollow to all existing and new external links. Copy the code into your functions.php of your activated theme
You can also call the function
home_url()
instead of"YOUR_DOMAIN_ADDRESS"
in the space provided to avoid hard coding of the domain name.The code is tested and it works. Hope this one helps.
You can use following snippet: http://wpsnipp.com/index.php/functions-php/nofollow-external-links-only-the_content-and-the_excerpt/
I think adding
rel"nofollow"
andtarget="_blank"
to outgoing links permanently is more work than it can be shown here. You will have to rebuild the functions of plugins like External Links so that even links in yourwp_nav_menus
can be rewritten.I have a suggestion that adds the desired attributes via JavaScript when the page is loaded. You can add this script directly to your theme header or you can keep it in a seperate file enqueing the script in your themes'
functions.php
:I took the answer of @rony-samuel and adjusted few things you might find useful.
Use the built-in
make_clickable
function to wrap links automatically. (E.g. useful when creating posts via API) - then check if the user has added additional classes to a link, (like abutton
to have a different styling) – we don't want to overwrite that, so just return the given markup with$m[0]
.Last thing is the regex. In combination with
make_clickable
it would output<a <a href...
so a link in a link. I corrected the regex to avoid that.