函数文档

status_header()

💡 云策文档标注

概述

status_header() 函数用于设置 HTTP 状态头,通过指定状态码和可选描述来生成并发送 HTTP 响应头。它支持自定义描述,并允许通过过滤器进行修改。

关键要点

  • 函数接受两个参数:必需的 HTTP 状态码 $code 和可选的描述 $description,后者默认为 get_status_header_desc() 的返回值。
  • 内部使用 wp_get_server_protocol() 获取服务器协议,并组合成状态头字符串。
  • 通过 apply_filters() 调用 'status_header' 过滤器,允许开发者修改状态头、代码、描述和协议。
  • 仅在 headers_sent() 返回 false 时发送头信息,避免重复发送。
  • 在 WordPress 4.4.0 版本中引入了 $description 参数,增强了自定义能力。

代码示例

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

注意事项

  • 自定义描述参数 $description 仅在没有默认状态码描述时生效,不会覆盖已设置的默认值。
  • 确保在发送任何输出前调用此函数,以避免 headers_sent() 返回 true 导致头信息无法发送。

📄 原文内容

Sets HTTP status header.

Description

See also

Parameters

$codeintrequired
HTTP status code.
$descriptionstringoptional
A custom description for the HTTP status.
Defaults to the result of get_status_header_desc() for the given code.

More Information

Usage:
status_header( $header );
Notes:

Uses: apply_filters() Calls ‘status_header‘ on status header string, HTTP code, HTTP code description, and protocol string as separate parameters.

Source

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

Hooks

apply_filters( ‘status_header’, string $status_header, int $code, string $description, string $protocol )

Filters an HTTP status header.

Changelog

Version Description
4.4.0 Added the $description parameter.
2.0.0 Introduced.

User Contributed Notes