Skip to content

Instantly share code, notes, and snippets.

@wormeyman
Forked from allybee/target_blank.js
Created December 3, 2020 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wormeyman/f253046a529b8eb0071c931d578342bb to your computer and use it in GitHub Desktop.
Save wormeyman/f253046a529b8eb0071c931d578342bb to your computer and use it in GitHub Desktop.
Add target="_blank" to external links with pure JavaScript. in WordPRess
add_action( 'wp_footer', function () { ?>
<script>
document.addEventListener("DOMContentLoaded", function () {
// remove subdomain of current site's url and setup regex
var internal = location.host.replace("www.", "");
internal = new RegExp(internal, "i");
var a = document.getElementsByTagName("a"); // then, grab every link on the page
for (var i = 0; i < a.length; i++) {
var href = a[i].host; // set the host of each link
if (!internal.test(href)) {
// make sure the href doesn't contain current site's host
a[i].setAttribute("target", "_blank"); // if it doesn't, set attributes
}
}
console.log('EJ Loaded page');
});
</script>
<?php } );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment