Published on October 6, 2019

How to automatically open external links in a new window/tab

Sridhar Katakam

This tutorial shows how links to external sites can be set to open automatically in a new window/tab when using Oxygen.

Here’s How

Edit the Main Catch All Template.

Add a Code Block at the very end below all other top-level Sections/elements.

PHP & HTML:

<?php
	// echo "hello world!";
?>

JavaScript:

(function($) {

	$('a')
	.filter('[href^="http"], [href^="//"]')
	.not('[href*="' + window.location.host + '"]')
	.attr({
		rel: 'noreferrer noopener',
		target: '_blank'
	})

}(jQuery));

Opening all Links in a Section in new window/tab

If you wish to open all the links inside a particular element, say a Section but not all external links throughout the site, use the following JS instead inside the particular Template/Page:

jQuery('#section-178-2 a').attr({
	target: "_blank",
	rel: "noreferrer noopener"
});

Replace section-178-2 with the ID of the parent container having the links.

References

https://gist.github.com/wpscholar/4637176

https://stackoverflow.com/a/13014355/778809

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right