The links_add_target() WordPress PHP function adds a target
attribute to all links in the passed content.
Usage
links_add_target( $content, $target = '_blank', $tags = array( 'a' ) );
Parameters
$content
(string) (Required): String to search for links in.$target
(string) (Optional): Thetarget
attribute to add to the links. Default: ‘_blank’.$tags
(array) (Optional): An array of tags to apply to. Default: array(‘a’).
More information
See WordPress Developer Resources: links_add_target()
Examples
Add target _blank to all anchor tags
This example adds the target="_blank"
attribute to all <a>
tags in the $content
string.
$content = 'Visit our <a href="https://example.com">website</a>!'; $new_content = links_add_target($content); echo $new_content; // Output: Visit our <a href="https://example.com" target="_blank" rel="noopener">website</a>!
Add target _self to all anchor tags
This example adds the target="_self"
attribute to all <a>
tags in the $content
string.
$content = 'Visit our <a href="https://example.com">website</a>!'; $new_content = links_add_target($content, '_self'); echo $new_content; // Output: Visit our <a href="https://example.com" target="_self" rel="noopener">website</a>!
Add target _blank to anchor and button tags
This example adds the target="_blank"
attribute to all <a>
and <button>
tags in the $content
string.
$content = 'Visit our <a href="https://example.com">website</a> or <button data-href="https://example.org">click me</button>!'; $new_content = links_add_target($content, '_blank', array('a', 'button')); echo $new_content; // Output: Visit our <a href="https://example.com" target="_blank" rel="noopener">website</a> or <button data-href="https://example.org" target="_blank">click me</button>!
Add target _parent to all anchor tags
This example adds the target="_parent"
attribute to all <a>
tags in the $content
string.
$content = 'Visit our <a href="https://example.com">website</a>!'; $new_content = links_add_target($content, '_parent'); echo $new_content; // Output: Visit our <a href="https://example.com" target="_parent" rel="noopener">website</a>!
Add target _top to all anchor tags
This example adds the target="_top"
attribute to all <a>
tags in the $content
string.
$content = 'Visit our <a href="https://example.com">website</a>!'; $new_content = links_add_target($content, '_top'); echo $new_content; // Output: Visit our <a href="https://example.com" target="_top" rel="noopener">website</a>!