WordPress is a great Content Management System, not just for bloggers …
One of the downsides I have run into is that links in comments automatically get reformatted and the HTML “target=_blank” gets stripped away so a link in a comment will always open in the same window as you website. Personally I prefer such a link to open in a new window …
So in this article a simple piece of code to make links in WordPress comments automatically open in a new window or a new tab by automatically adding “target=_blank” to links in comments.
Modify Comments to have links in comments open in a new window or tab
For this we are going add a filter in the functions.php file of your theme.
I prefer this kind of an approach over a plugin, since I’m fully in control of what’s happening … you might understand this reasoning when you’ve used plugins before that were abandoned after a while …
Add the following code to your functions.php of your theme:
return str_replace('<a', '<a target="_blank"', $text);
This does two things:
1. Creates a function
t4a_comment_links_in_new_window which takes a string and replaces every ocurance of
<a (from the HTML A HFER tag) and replaces it with
2. Add this function to the
comment_text filter so that it’s being called when a comment is being filtered.
The result is that any link in a comment will now open in a new window or a new tab.
Please note that this can also be achieved with plugins like for example No Follow for External Link (the name is a bit misleading, bt it does the trick).
Donations are very much appreciated, but not required. Donations will be used for web-hosting expenses, project hardware or a motivational boost (a drink or snack). Thank you very much for those have donated already! It's truly AwEsOmE to see that folks like our articles and small applications.
Please note that clicking affliate links, like the ones from Amazon, may result in a small commission for us - which we highly appreciate as well.