Page 1 of 1

WordPress – Open links in comments in a new Window or Tab

WordPress – Open links in comments in a new Window or Tab
   0

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:


1
2
3
4
5
6
function t4a_comment_links_in_new_window($text)
{
    return str_replace('<a', '<a target="_blank"', $text);
}

add_filter('comment_text', 't4a_comment_links_in_new_window');

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 <a target="_blank".

2. Add this function to thecomment_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).

Donation options


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.

Comments


There are no comments yet.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.



Your Comment …

Friendly request to not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.
Tweaking4All will never share your email address with others.