wp_robots()WP 5.7.0

Outputs the meta tag robots.

Combines all existing directives, cleans them, and outputs them in the robots meta tag:

<meta name='robots' content='directive, directive'>

<!-- for example -->
<meta name='robots' content='noindex, follow, max-image-preview:large' />

The function is automatically called by the WordPress core on the wp_head event so that the robots meta tag is output automatically where necessary. This is done with such a hook in the core:

add_action( 'wp_head', 'wp_robots', 1 );

Therefore, the plugin or theme should not call this function separately. In special cases, for example, when the template does not use wp_head(), a new function can be hooked to its filter or called directly in the code:

// hooking to the filter
add_action( 'my_custom_template_head', 'wp_robots' );

// direct call
<?php wp_robots() ?>
Hooks from the function

Returns

null. Outputs HTML code to the screen.

Usage

wp_robots();

Examples

0

#1 Example of adding a custom directive to the robots meta tag

This example shows how to add the directive follow to existing robots meta tag directives.

To add your own directives, you need to use wp_robots hook. It takes an array where in the key you need to specify the name of the directive, and in the value its value.

add_filter( 'wp_robots', 'my_wp_robots_add_follow' );

function my_wp_robots_add_follow( $robots ) {
	$robots['follow'] = true;

	return $robots;
}

Changelog

Since 5.7.0 Introduced.
Since 5.7.1 No longer prevents specific directives to occur together.

wp_robots() code WP 6.8.3

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";
}