wp_targeted_link_rel()
云策文档标注
概述
wp_targeted_link_rel() 是一个已弃用的 WordPress 函数,用于向所有带有 target 属性的 HTML A 元素添加 rel="noopener" 属性,以增强安全性。
关键要点
- 函数 wp_targeted_link_rel() 在 WordPress 6.7.0 版本中被弃用,开发者应避免使用。
- 它接受一个字符串参数 $text,可能包含 HTML A 元素,并返回转换后的内容字符串。
- 函数内部使用正则表达式匹配和回调函数 wp_targeted_link_rel_callback 来处理链接,跳过 script 和 style 标签。
- 从 WordPress 5.6.0 版本起,移除了 'noreferrer' 关系,仅保留 'noopener'。
- 相关函数包括 _deprecated_function() 用于标记弃用,is_serialized() 用于检查序列化值。
代码示例
function wp_targeted_link_rel( $text ) {
_deprecated_function( __FUNCTION__, '6.7.0' );
// Don't run (more expensive) regex if no links with targets.
if ( false === stripos( $text, 'target' ) || false === stripos( $text, '/si';
preg_match_all( $script_and_style_regex, $text, $matches );
$extra_parts = $matches[0];
$html_parts = preg_split( $script_and_style_regex, $text );
foreach ( $html_parts as &$part ) {
$part = preg_replace_callback( '|]*targets*=[^>]*)>|i', 'wp_targeted_link_rel_callback', $part );
}
$text = '';
for ( $i = 0; $i < count( $html_parts ); $i++ ) {
$text .= $html_parts[$i];
if ( isset( $extra_parts[$i] ) ) {
$text .= $extra_parts[$i];
}
}
return $text;
}注意事项
- 此函数已弃用,建议开发者寻找替代方案或更新代码以避免依赖。
- 在处理 HTML 内容时,需注意正则表达式的性能影响,函数已包含优化以避免不必要的处理。
- 用户贡献笔记中提到,从 WordPress 5.1.0 起,此函数可用于向任何 HTML 代码添加 rel 属性,示例在 wp-includes/widgets/class-wp-widget-text.php 中。
原文内容
Adds rel="noopener" to all HTML A elements that have a target.
Parameters
$textstringrequired-
Content that may contain HTML A elements.
Source
function wp_targeted_link_rel( $text ) {
_deprecated_function( __FUNCTION__, '6.7.0' );
// Don't run (more expensive) regex if no links with targets.
if ( false === stripos( $text, 'target' ) || false === stripos( $text, '<a ' ) || is_serialized( $text ) ) {
return $text;
}
$script_and_style_regex = '/<(script|style).*?</\1>/si';
preg_match_all( $script_and_style_regex, $text, $matches );
$extra_parts = $matches[0];
$html_parts = preg_split( $script_and_style_regex, $text );
foreach ( $html_parts as &$part ) {
$part = preg_replace_callback( '|<as([^>]*targets*=[^>]*)>|i', 'wp_targeted_link_rel_callback', $part );
}
$text = '';
for ( $i = 0; $i < count( $html_parts ); $i++ ) {
$text .= $html_parts[ $i ];
if ( isset( $extra_parts[ $i ] ) ) {
$text .= $extra_parts[ $i ];
}
}
return $text;
}
Skip to note 2 content
Jb Audras
Since WP 5.1.0, we can add
relattributes to any bit of HTML code.Example used in
wp-includes/widgets/class-wp-widget-text.php: