函数文档

wp_robots_no_robots()

💡 云策文档标注

概述

wp_robots_no_robots() 是一个 WordPress 函数,用于向 robots 元标签添加 noindex 指令,以阻止搜索引擎索引页面内容。它通常作为 'wp_robots' 过滤器的回调函数使用。

关键要点

  • 函数功能:将 noindex 添加到 robots 元标签,并根据博客公开设置自动设置 follow 或 nofollow。
  • 参数:接受一个关联数组 $robots,表示 robots 指令。
  • 返回值:返回过滤后的 robots 指令数组。
  • 典型用法:通过 add_filter('wp_robots', 'wp_robots_no_robots') 作为回调函数。
  • 相关函数:与 wp_robots_noindex()、wp_robots_noindex_embeds() 和 wp_robots_noindex_search() 类似,用于特定场景的 noindex 添加。
  • 版本历史:自 WordPress 5.7.0 引入。

代码示例

// 示例1:使用 add_action 和匿名函数,在 wp_head 中条件添加过滤器
add_action( 
    'wp_head',
    function() {
        is_tax( 'post_format' ) && add_filter( 'wp_robots', 'wp_robots_no_robots' );
    },
    0
);

// 示例2:使用 add_filter 和匿名函数,直接调用 wp_robots_no_robots
add_filter(
    'wp_robots',
    function ( array $robots ) {
        if ( is_tax( 'post_format' ) ) {
            return wp_robots_no_robots( $robots );
        }
        return $robots;
    }
);

注意事项

  • 在示例1中,优先级设为 0 以确保动作及时执行,避免运行过晚。
  • 函数内部使用 get_option('blog_public') 来决定 follow 或 nofollow,需确保博客公开设置正确配置。

📄 原文内容

Adds noindex to the robots meta tag.

Description

This directive tells web robots not to index the page content.

Typical usage is as a ‘wp_robots’ callback:

add_filter( 'wp_robots', 'wp_robots_no_robots' );

Parameters

$robotsarrayrequired
Associative array of robots directives.

Return

array Filtered robots directives.

Source

function wp_robots_no_robots( array $robots ) {
	$robots['noindex'] = true;

	if ( get_option( 'blog_public' ) ) {
		$robots['follow'] = true;
	} else {
		$robots['nofollow'] = true;
	}

	return $robots;
}

Changelog

Version Description
5.7.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Two examples, both adding noindex to all Post Format archives:

    add_action( 
        'wp_head',
        function() {
            is_tax( 'post_format' ) && add_filter( 'wp_robots', 'wp_robots_no_robots' );
        },
        0
    );

    (Note: a priority of 0 otherwise the action runs too late.)

    add_filter(
        'wp_robots',
        function ( array $robots ) {
            if ( is_tax( 'post_format' ) ) {
                return wp_robots_no_robots( $robots );
            }
            return $robots;
        }
    );