links_add_target()
云策文档标注
概述
links_add_target() 是一个 WordPress 函数,用于向传入内容中的所有链接添加 target 属性。默认情况下,它仅应用于 <a> 标签,但可通过参数自定义。
关键要点
- 函数功能:向内容中的链接添加指定的 target 属性,并替换现有 target 属性。
- 参数说明:$content(必需,要搜索链接的字符串)、$target(必需,要添加的目标,默认为 '_blank')、$tags(可选,要应用的标签数组,默认为 array('a'))。
- 返回值:返回处理后的字符串内容。
- 内部实现:使用 preg_replace_callback 和全局变量 $_links_add_target 进行正则替换。
代码示例
$cat_links = get_the_category_list();
$modified = links_add_target( $cat_links ); // 省略 'target' 参数,默认为 _blank
echo $modified;注意事项
- 任何现有的 target 属性都会被剥离并替换为新值。
- 可通过 $tags 参数扩展应用到其他 HTML 标签,如 'img' 等。
原文内容
Adds a target attribute to all links in passed content.
Description
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.
Parameters
$contentstringrequired-
String to search for links in.
$targetstringrequired-
The target to add to the links.
$tagsstring[]optional-
An array of tags to apply to.
Default:
array()
Source
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 );
}
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |
Skip to note 2 content
Saurabh Sharma
Add
target="_blank"to theget_the_category_list()output.$cat_links = get_the_category_list(); $modified = links_add_target( $cat_links ); // the 'target' parameter is omitted as it is _blank by default echo $modified;