Last active
February 1, 2022 16:33
-
-
Save georgestephanis/40c11157ff04a8c3f4d5894f06ab5443 to your computer and use it in GitHub Desktop.
Tiny WordPress plugin for how to force external links to open in a new tab.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global externalLinksNewTab */ | |
jQuery( document.body ).on( 'click', 'a', function( event ) { | |
if ( ! this.href ) { | |
return; | |
} | |
// If a target is already specified, let that win. | |
if ( this.target ) { | |
return; | |
} | |
let internalHosts = [ | |
window.location.host.toLowerCase(), | |
externalLinksNewTab.siteUrlDomain.toLowerCase() | |
]; | |
let hrefHost = new URL( this.href, window.location ).hostname.toLowerCase(); | |
if ( -1 === internalHosts.findIndex( host => host === hrefHost ) ) { | |
// External! | |
event.preventDefault(); | |
event.stopPropagation(); | |
window.open( this.href, '_blank' ); | |
return false; | |
} | |
} ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin name: Open External Links in a New Tab! | |
* Author: George Stephanis | |
* Author URI: https://georgestephanis.wordpress.com | |
* Version: 1.0 | |
* License: GPLv2+ | |
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt | |
*/ | |
add_action( | |
'wp_enqueue_scripts', | |
function() { | |
wp_enqueue_script( | |
'external-links-new-tab', | |
plugins_url( 'external-links-new-tab.js', __FILE__ ), | |
array( | |
'jquery', | |
), | |
filemtime( __DIR__ . '/external-links-new-tab.js' ), // version | |
true // in footer | |
); | |
wp_localize_script( | |
'external-links-new-tab', | |
'externalLinksNewTab', | |
array( | |
'siteUrlDomain' => wp_parse_url( site_url(), PHP_URL_HOST ), | |
) | |
); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment