Open All External Links in New Window and/or Add noreferrer noopener - WordPress Tips, Tricks Every Serious Blogger Must Know

 



Open All External Links in New Window and/or Add noreferrer noopener - WordPress Tips, Tricks Every Serious Blogger Must Know



To open all external links in a new window, or add a noreferrer and noopener attribute to all external links, all you need to do is to install a plugin called WP External Links.For the Open external links option, select each in a separate new window or tab. You can leave other settings on default and you’re good to go.

If you want to do this manually follow the instructions below.

Add the following code snippet at the end of the theme’s functions.php file:

add_action( 'wp_enqueue_scripts', 'external_links' );
function external_links() {
    wp_enqueue_script(
        'external_links.js',
        get_template_directory_uri() . '/js/external_links.js', 
        array('jquery')
    );
}

Next, create a folder called “js” inside your theme’s folder and inside it, create a script file called external_links.js and then copy and paste the following code snippet in the said file:

jQuery(document).ready(function($) {
    // Check if links are external, if yes, add class=external and add proper attributes
    $('a').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).addClass("external").attr("rel","external noopener noreferrer").attr("target","_blank");
});

Now all external links will open in the new tab and will have externalnoopener, and noreferrer attributes.

After installing the plugin, you will have a new item in your admin navigation menu called “External Links”. Go here and configure the plugin.





Previous Post Next Post

 

Advertisement