| |

How to open all external links in New Window or New Tab without a WordPress plugin

Do you want to open external links from your blog posts in a new window?

Opening external links in a new window allow your users to visit the link without leaving your website. I will also show different code snippets to do that, so you can choose the one that works for you.

For this, you can go through the child theme approach or add an external plugin.

Below is the link to one of the plugin :

Vanilla Javascript Snippet:

<script>
function externalLinks() {
  for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
    var b = c[a];
    b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
  }
}
;
externalLinks();
<script>

jQuery Code Snippet #1

jQuery(document).ready(function($){
$("a[href^=http]").each(function(){
      if(this.href.indexOf(location.hostname) == -1) {
         $(this).attr({
            target: "_blank",
            title: "Opens in a new window"
         });
      }
   })
});

jQuery Code Snippet #2

jQuery(document).ready(function($) {
    $('a').each(function() {
        var a = new RegExp('/' + window.location.host + '/');
        if (!a.test(this.href)) {
            $(this).click(function(event) {
                event.preventDefault();
                event.stopPropagation();
                window.open(this.href, '_blank');
            });
        }
    });
});

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

One Comment

  1. Hi I got a snippet to add check box registration box… it works ok but need to add link to Privacy policy. Can you help?