links_add_target()
Adds the target attribute with the specified value to all links (A tags) in the given text.
By default the function processes only <a> tags, but this behavior can be changed by specifying the tag names in the third parameter.
All existing target attributes will be removed and replaced with the new value.
1 time — 0.000099 sec (very fast) | 50000 times — 0.38 sec (very fast) | PHP 7.0.8, WP 4.6
No Hooks.
Returns
String. Formatted text.
Usage
links_add_target( $content, $target, $tags );
- $content(string) (required)
- A string in which to process the HTML tags specified in the third parameter.
- $target(string)
- The value of the target attribute to set on all tags.
Default: '_blank' - $tags(array)
- An array of HTML tags to which the target attribute should be added.
Default: array('a')
Examples
#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> */
#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() links add target code WP 6.8.3
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 );
}