links_add_target

Adds a Target attribute to all links in passed content.

Description

(string) links_add_target( (string) $content, (string) $target = '_blank', (array) $tags = array() ); 

This function by default only applies to tags, however this can be modified by the 3rd param.

*NOTE:* Any current target attributed will be stripped and replaced.

Returns (string)

The processed content.

Parameters (3)

0. $content (string)
String to search for links in.
1. $target — Optional. (string) => '_blank'
The Target to add to the links.
2. $tags — Optional. (array) => array()
An array of tags to apply to.

Usage

  1. if ( !function_exists( 'links_add_target' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // String to search for links in. 
  5. $content = ''; 
  6.  
  7. // The Target to add to the links. 
  8. $target = '_blank'; 
  9.  
  10. // An array of tags to apply to. 
  11. $tags = array(); 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = links_add_target($content, $target, $tags); 
  15.  

Defined (2)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function links_add_target( $content, $target = '_blank', $tags = array('a') ) { 
  2. global $_links_add_target; 
  3. $_links_add_target = $target; 
  4. $tags = implode('|', (array)$tags); 
  5. return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content ); 
  1. function _links_add_target( $m ) { 
  2. global $_links_add_target; 
  3. $tag = $m[1]; 
  4. $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]); 
  5. return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';