links_add_target()WP 2.7.0

Adds a Target attribute to all links in passed content.

By default, this function only applies to <a> tags. However, this can be modified via the $tags parameter.

NOTE: Any current target attribute will be stripped and replaced.

1 time — 0.000099 sec (very fast) | 50000 times — 0.38 sec (very fast) | PHP 7.0.8, WP 4.6

No Hooks.

Return

String. The processed content.

Usage

links_add_target( $content, $target, $tags );
$content(string) (required)
String to search for links in.
$target(string)
The target to add to the links.
Default: '_blank'
$tags(string[])
An array of tags to apply to.
Default: array( fooo )

Examples

0

#1 Add the attribute target=_blank to all links in the text

$text = 'The task of the organization, especially the <a href="#">further</a>
development <a href="#" target="_self">various forms.</a>';

$text = links_add_target( $text );

echo $text;

/* will output:
The task of the organization, especially the <a href="#" target="_blank">further</a>
development <a href="#" target="_blank">various forms.</a>
*/
0

#2 Add target="_blank" to all external links only

Unfortunately, this function adds target to ALL links inside the passed text, not only to external ones. I came up with this solution, maybe it will be useful for someone:

// target="_blank" только для внешних ссылок
add_filter( 'the_content', 'external_links_new_tab' );

function external_links_new_tab( $content ){

	$content = wp_unslash( wp_rel_nofollow( $content ) );
	$content = str_replace( 'rel="nofollow"', 'target="_blank"', $content );

	return $content;
}

Notes

  • Global. String. $_links_add_target

Changelog

Since 2.7.0 Introduced.

links_add_target() code WP 6.5.2

function links_add_target( $content, $target = '_blank', $tags = array( 'a' ) ) {
	global $_links_add_target;
	$_links_add_target = $target;
	$tags              = implode( '|', (array) $tags );
	return preg_replace_callback( "!<($tags)((\s[^>]*)?)>!i", '_links_add_target', $content );
}