status_header()WP 2.0.0

Set HTTP status header.

Hooks from the function

Return

null. Nothing.

Usage

status_header( $code, $description );
$code(int) (required)
HTTP status code.
$description(string)
A custom description for the HTTP status.
Default: ''

Examples

0

#1 Сlose all site from indexing

Suppose you want to change the status code for all pages: you need to close all pages of the site from indexing.

To do this, add this code to functions.php:

add_action( 'wp', function(){
	status_header( 503 ); 
} );
0

#2 Setting the 404 status to a specific post

Suppose we need to set 404 status for all post types event, depending on the status. I.e. we have an event, if it is not active, we need to give it a 404 status and display a 404 page code for it.

add_action( 'template_redirect', 'rr_404_my_event', 1 );

// this code prints a 404 page for an inactive event
// and sets the status to 404
function rr_404_my_event() {
	global $post, $wp_query;

	if ( is_singular( 'event' ) && ! rr_event_should_be_available( $post->ID ) ) {

		// put a status
		$wp_query->set_404();
		status_header(404);

		// output the 404.php file
		include( get_query_template( '404' ) );

		exit;
	}
}

The rrr_event_should_be_available() function checks if the current post should be available.

Notes

Changelog

Since 2.0.0 Introduced.
Since 4.4.0 Added the $description parameter.

status_header() code WP 6.1.1

function status_header( $code, $description = '' ) {
	if ( ! $description ) {
		$description = get_status_header_desc( $code );
	}

	if ( empty( $description ) ) {
		return;
	}

	$protocol      = wp_get_server_protocol();
	$status_header = "$protocol $code $description";
	if ( function_exists( 'apply_filters' ) ) {

		/**
		 * Filters an HTTP status header.
		 *
		 * @since 2.2.0
		 *
		 * @param string $status_header HTTP status header.
		 * @param int    $code          HTTP status code.
		 * @param string $description   Description for the status code.
		 * @param string $protocol      Server protocol.
		 */
		$status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
	}

	if ( ! headers_sent() ) {
		header( $status_header, true, $code );
	}
}