How Do I Make an External Link Open in a New Tab in WordPress?

Making an external link open in a new tab in WordPress is easy. Simply add the following code to your theme’s functions.

php file:
I’ve placed this code in the functions.php file of my WordPress theme so that it will work for all my themes.

function openInNewTab() {

if (is_front_page()) {

wp_die(__(‘External link cannot be opened in a new tab.’), E_USER_ERROR);
}

else {

$new_tab = wp_get_current_tab();

$url = get_post_meta($post->ID, ‘_link’, true);

if ($url) {

$new_tab = $url;

}

add_action(‘wp_loaded’, ‘openInNewTab’);

The first line of this function will check to see if the page is the front page. If it is, the function will simply die. If the page isn’t the front page, the function will get the current tab number and use that to determine what tab the user should be in.

The function then checks to see if the link is in the post meta _link field. If it is, the function will change the current tab to the URL that is in the post meta _link field.