wp_rel_callback()
云策文档标注
概述
wp_rel_callback() 是一个回调函数,用于向 HTML A 元素添加 rel 属性。它会移除已存在的字符串以避免无效的 (X)HTML,并处理内部链接的特殊情况。
关键要点
- 函数用途:作为回调函数,在匹配的 HTML A 元素中添加指定的 rel 属性。
- 参数:接受 $matches(数组,必需)和 $rel(字符串,必需)两个参数,分别表示匹配结果和要添加的 rel 属性。
- 返回值:返回添加了 rel 属性的 HTML A 元素字符串。
- 内部链接处理:如果链接是内部链接,会从 rel 中移除 'nofollow'。
- 属性合并:如果 A 元素已有 rel 属性,会合并新旧值并去重。
- 相关函数:与 wp_is_internal_link()、wp_kses_hair()、wp_allowed_protocols() 和 esc_attr() 等函数协同工作。
- 使用场景:被 wp_rel_ugc()、wp_rel_nofollow() 和 wp_rel_nofollow_callback() 等函数调用。
- 版本历史:自 WordPress 5.3.0 版本引入。
代码示例
function wp_rel_callback( $matches, $rel ) {
$text = $matches[1];
$atts = wp_kses_hair( $matches[1], wp_allowed_protocols() );
if ( ! empty( $atts['href'] ) && wp_is_internal_link( $atts['href']['value'] ) ) {
$rel = trim( str_replace( 'nofollow', '', $rel ) );
}
if ( ! empty( $atts['rel'] ) ) {
$parts = array_map( 'trim', explode( ' ', $atts['rel']['value'] ) );
$rel_array = array_map( 'trim', explode( ' ', $rel ) );
$parts = array_unique( array_merge( $parts, $rel_array ) );
$rel = implode( ' ', $parts );
unset( $atts['rel'] );
$html = '';
foreach ( $atts as $name => $value ) {
if ( isset( $value['vless'] ) && 'y' === $value['vless'] ) {
$html .= $name . ' ';
} else {
$html .= "{$name}="" . esc_attr( $value['value'] ) . '" ';
}
}
$text = trim( $html );
}
$rel_attr = $rel ? ' rel="' . esc_attr( $rel ) . '"' : '';
return "<a{$rel_attr}>{$text}</a>";
}
原文内容
Callback to add a rel attribute to HTML A element.
Description
Will remove already existing string before adding to prevent invalidating (X)HTML.
Parameters
$matchesarrayrequired-
Single match.
$relstringrequired-
The rel attribute to add.
Source
function wp_rel_callback( $matches, $rel ) {
$text = $matches[1];
$atts = wp_kses_hair( $matches[1], wp_allowed_protocols() );
if ( ! empty( $atts['href'] ) && wp_is_internal_link( $atts['href']['value'] ) ) {
$rel = trim( str_replace( 'nofollow', '', $rel ) );
}
if ( ! empty( $atts['rel'] ) ) {
$parts = array_map( 'trim', explode( ' ', $atts['rel']['value'] ) );
$rel_array = array_map( 'trim', explode( ' ', $rel ) );
$parts = array_unique( array_merge( $parts, $rel_array ) );
$rel = implode( ' ', $parts );
unset( $atts['rel'] );
$html = '';
foreach ( $atts as $name => $value ) {
if ( isset( $value['vless'] ) && 'y' === $value['vless'] ) {
$html .= $name . ' ';
} else {
$html .= "{$name}="" . esc_attr( $value['value'] ) . '" ';
}
}
$text = trim( $html );
}
$rel_attr = $rel ? ' rel="' . esc_attr( $rel ) . '"' : '';
return "<a {$text}{$rel_attr}>";
}
Changelog
| Version | Description |
|---|---|
| 5.3.0 | Introduced. |