钩子文档

wp_robots

💡 云策文档标注

概述

wp_robots 是一个 WordPress 过滤器,用于控制 robots 元标签中的指令。它允许开发者动态修改搜索引擎爬虫的索引行为,仅在必要时生成元标签。

关键要点

  • 过滤器名称:wp_robots,通过 apply_filters 调用,参数为关联数组 $robots。
  • 参数结构:$robots 是关联数组,键为指令名(如 'noindex'),值为字符串(指令值)或布尔值 true(布尔指令)。
  • 相关函数:wp_robots() 函数在 wp-includes/robots-template.php 中定义,用于显示 robots 元标签。
  • 版本历史:从 WordPress 5.7.0 版本引入。

代码示例

// 示例1:添加 noindex 指令
add_filter( 'wp_robots', function( $robots ) {
	$robots['noindex'] = true;
	return $robots;
} );

// 示例2:基于页面ID控制 noindex 指令
add_filter( 'wp_robots', function( $robots ) {
	$id = get_the_ID();
	if ( 19 === $id ) {
		$robots['noindex'] = true;
	}
	return $robots;
} );

注意事项

  • 代码应放置在 wp_header() 调用之前,例如在页面模板或 functions.php 文件中。
  • 使用 get_the_ID() 等函数可实现更精细的页面控制,但需确保在适当上下文中调用。

📄 原文内容

Filters the directives to be included in the ‘robots’ meta tag.

Description

The meta tag will only be included as necessary.

Parameters

$robotsarray
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.

Source

$robots = apply_filters( 'wp_robots', array() );

Changelog

Version Description
5.7.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example of adding a noindex robots tag.

    add_filter( 'wp_robots', function( $robots ) {
    	$robots['noindex'] = true;
    
    	return $robots;
    } );

    To affect pages with a certain page template, you can add this directly to the template, as long as it’s above the call to wp_header().

    To have more granular control over what pages are affected, you can add the snippet to your functions.php file and work with the current page inside the function:

    add_filter( 'wp_robots', function( $robots ) {
    	$id = get_the_ID();
    
    	if ( 19 === $id ) {
    		$robots['noindex'] = true;
    	}
    
    	return $robots;
    } );