One of the coolest features of WordPress is that you can filter items in your posts and this is a modification of something I whipped up before (and re-use all the time).
Try this plugin. Create a file in your wp-content/plugins
called target-blank.php
and put these contents into that file.
<?php
/*
Plugin Name: Add target="_blank" to external links
Description: This will filter links in posts and pages and add target="_blank" to those links
Version: 1.0
Author: Jan Dembowski
Author URI: https://blog.dembowski.net/
*/
add_filter( 'the_content' , 'mh_add_blank' );
// add_filter( 'comment_text' , 'mh_add_blank' );
function mh_add_blank( $content ) {
// Regex to put all <a href="https://some-url-here/path/etc" into an array
$mh_url_regex = "/\<a\ href\=\"(http|https)\:\/\/[a-zA-Z0-9\-\.]+[a-zA-Z]{2,3}.*\"[\ >]/";
preg_match_all( $mh_url_regex , $content, $mh_matches );
// Go through that array and add target="_blank" to external links
for ( $mh_count = 0; $mh_count < count( $mh_matches[0] ); $mh_count++ )
{
$mh_old_url = $mh_matches[0][$mh_count];
// $mh_new_url = str_replace( '" ' , '" target="_blank" ' , $mh_matches[0][$mh_count] );
$mh_new_url = str_replace( '">' , '" target="_blank">' , $mh_matches[0][$mh_count] );
// Array of destinations we don't want to apply the hack to.
// Your home URL will get excluded but you can add to this array.
// Partial matches work here, the more specific the better.
$mh_ignore = array(
home_url( '/' ),
'www.ads-software.com/'
);
// Make the substitution on all links except the ignore list
if( !mh_array_find( $mh_old_url , $mh_ignore ) )
$content = str_replace( $mh_old_url , $mh_new_url , $content );
}
return $content;
}
// Only see if the array element is contained in the string
function mh_array_find( $needle , $haystack ) {
if(!is_array($haystack)) return false;
foreach ($haystack as $key=>$item) {
// See if the item is in the needle
if (strpos($needle, $item ) !== false) return true;
}
return false;
}
https://pastebin.com/7dXbUNGw
Once you’ve saved that file go to your WordPress plugins and activate the plugin called Add target="_blank" to external links
. That should make all links in your post open in a new window or tab provided that link does not point to your own site.
If you have additional server names you want to exclude from this then add that to the array $mh_ignore
and those will get excluded too.
If anything goes really wrong then just delete that target-blank.php
file.