wp_robots()
云策文档标注
概述
wp_robots() 函数用于在必要时输出 robots 元标签,通过 'wp_robots' 过滤器收集指令并处理。
关键要点
- 函数通过 apply_filters('wp_robots', array()) 收集 robots 指令数组,键为指令名,值为字符串或布尔 true。
- 指令被处理为字符串格式:若值为字符串,输出为“指令:值”;若值为真布尔值,仅输出指令名。
- 若无相关指令,函数不输出任何内容;否则输出 robots 元标签。
代码示例
function wp_robots() {
$robots = apply_filters( 'wp_robots', array() );
$robots_strings = array();
foreach ( $robots as $directive => $value ) {
if ( is_string( $value ) ) {
$robots_strings[] = "{$directive}:{$value}";
} elseif ( $value ) {
$robots_strings[] = $directive;
}
}
if ( empty( $robots_strings ) ) {
return;
}
echo "n";
}注意事项
- 使用 'wp_robots' 过滤器可自定义 robots 指令,确保键值对格式正确。
- 函数从 WordPress 5.7.0 引入,5.7.1 版本不再阻止特定指令共存。
原文内容
Displays the robots meta tag as necessary.
Description
Gathers robots directives to include for the current context, using the ‘wp_robots’ filter. The directives are then sanitized, and the robots meta tag is output if there is at least one relevant directive.
Source
function wp_robots() {
/**
* Filters the directives to be included in the 'robots' meta tag.
*
* The meta tag will only be included as necessary.
*
* @since 5.7.0
*
* @param array $robots Associative array of directives. Every key must be the name of the directive, and the
* corresponding value must either be a string to provide as value for the directive or a
* boolean `true` if it is a boolean directive, i.e. without a value.
*/
$robots = apply_filters( 'wp_robots', array() );
$robots_strings = array();
foreach ( $robots as $directive => $value ) {
if ( is_string( $value ) ) {
// If a string value, include it as value for the directive.
$robots_strings[] = "{$directive}:{$value}";
} elseif ( $value ) {
// Otherwise, include the directive if it is truthy.
$robots_strings[] = $directive;
}
}
if ( empty( $robots_strings ) ) {
return;
}
echo "<meta name='robots' content='" . esc_attr( implode( ', ', $robots_strings ) ) . "' />n";
}
Hooks
- apply_filters( ‘wp_robots’, array $robots )
-
Filters the directives to be included in the ‘robots’ meta tag.