wp_redirect
云策文档标注
概述
wp_redirect 是一个 WordPress 过滤器钩子,允许开发者在执行重定向前修改重定向 URL 和 HTTP 状态码。它常用于自定义或验证重定向目标,或调整响应代码以满足特定需求。
关键要点
- wp_redirect 钩子通过 apply_filters( 'wp_redirect', $location, $status ) 调用,参数包括重定向路径或 URL ($location) 和 HTTP 状态码 ($status)。
- 开发者可以使用 add_filter 添加回调函数来修改 $location 或 $status,例如基于 URL 内容调整状态码。
- 注意:wp_redirect 钩子仅能修改 $location 值;要修改 $status 值,应使用 wp_redirect_status 钩子。
代码示例
add_filter( 'wp_redirect', 'wpdocs_modify_redirect_status', 10, 2 );
function wpdocs_modify_redirect_status( $location, $status ) {
if ( strpos( $location, 'permanent' ) !== false ) {
$status = 301; // Permanent redirect
}
return apply_filters( 'wp_redirect', $location, $status );
}注意事项
此钩子仅能改变 $location 值。要改变 $status 值,请使用 wp_redirect_status 钩子。
原文内容
Filters the redirect location.
Parameters
$locationstring-
The path or URL to redirect to.
$statusint-
The HTTP response status code to use.
Source
$location = apply_filters( 'wp_redirect', $location, $status );
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |
Skip to note 2 content
Noruzzaman
Overview of wp_redirect Hook
The
apply_filters( 'wp_redirect', string $location, int $status )hook in WordPress allows developers to modify the redirect URL ($location) and the HTTP status code ($status) before WordPress executes a redirection. This can be useful for modifying or validating the destination URL or for changing the response code to suit specific needs.add_filter( 'wp_redirect', 'wpdocs_modify_redirect_status', 10, 2 ); function wpdocs_modify_redirect_status( $location, $status ) { if ( strpos( $location, 'permanent' ) !== false ) { $status = 301; // Permanent redirect } return apply_filters( 'wp_redirect', $location, $status ); }In this example, if the redirect URL contains “permanent,” the status code changes to 301.
$locationvalue. To change the$statusvalue, use thewp_redirect_statushook.