函数文档

wp_redirect()

💡 云策文档标注

概述

wp_redirect() 是 WordPress 中用于执行页面重定向的核心函数,支持自定义重定向位置、HTTP 状态码和 X-Redirect-By 头信息。开发者需注意该函数不会自动终止脚本执行,通常需要配合 exit 或 die 使用。

关键要点

  • 函数不会自动退出,建议在调用后添加 exit; 或 die; 以确保重定向生效。
  • 支持三个参数:$location(必需,重定向路径或URL)、$status(可选,HTTP状态码,默认302)、$x_redirect_by(可选,重定向应用标识,默认'WordPress')。
  • 返回布尔值:重定向被取消时返回 false,否则返回 true。
  • 提供过滤器钩子:wp_redirect 用于修改重定向位置,wp_redirect_status 用于修改状态码,x_redirect_by 用于修改 X-Redirect-By 头。
  • 存在安全风险:不验证 $location 是否指向当前主机,易受开放重定向攻击,建议优先使用 wp_safe_redirect() 进行安全重定向。
  • 相关函数包括 wp_safe_redirect()、wp_validate_redirect() 等,用于增强重定向安全性。

代码示例

// 基本用法,重定向后退出
wp_redirect( $url );
exit;

// 使用条件判断和过滤器
if ( wp_redirect( $url ) ) {
    exit;
}

// 安全重定向示例,避免开放重定向
wp_safe_redirect( $url );

// 硬编码重定向到外部站点
wp_redirect( 'https://example.com/some/page' );

// 在 template_redirect 钩子中使用
function my_logged_in_redirect() {
    if ( is_user_logged_in() && is_page( 12 ) ) {
        wp_redirect( get_permalink( 32 ) );
        die;
    }
}
add_action( 'template_redirect', 'my_logged_in_redirect' );

注意事项

  • 为避免浏览器缓存重定向页面导致意外行为,可在 wp_redirect() 前调用 nocache_headers() 函数。
  • 使用 301 状态码进行永久重定向时,需明确设置 $status 参数。
  • 在重定向到用户提供的 URL 时,务必使用 wp_safe_redirect() 或手动验证,以防止安全漏洞。

📄 原文内容

Redirects to another page.

Description

Note: wp_redirect() does not exit automatically, and should almost always be followed by a call to exit;:

wp_redirect( $url );
exit;

Exiting can also be selectively manipulated by using wp_redirect() as a conditional in conjunction with the ‘wp_redirect’ and ‘wp_redirect_status’ filters:

if ( wp_redirect( $url ) ) {
    exit;
}

Parameters

$locationstringrequired
The path or URL to redirect to.
$statusintoptional
HTTP response status code to use. Default '302' (Moved Temporarily).

Default:302

$x_redirect_bystring|falseoptional
The application doing the redirect or false to omit. Default 'WordPress'.

Return

bool False if the redirect was canceled, true otherwise.

Source

function wp_redirect( $location, $status = 302, $x_redirect_by = 'WordPress' ) {
	global $is_IIS;

	/**
	 * Filters the redirect location.
	 *
	 * @since 2.1.0
	 *
	 * @param string $location The path or URL to redirect to.
	 * @param int    $status   The HTTP response status code to use.
	 */
	$location = apply_filters( 'wp_redirect', $location, $status );

	/**
	 * Filters the redirect HTTP response status code to use.
	 *
	 * @since 2.3.0
	 *
	 * @param int    $status   The HTTP response status code to use.
	 * @param string $location The path or URL to redirect to.
	 */
	$status = apply_filters( 'wp_redirect_status', $status, $location );

	if ( ! $location ) {
		return false;
	}

	if ( $status < 300 || 399 < $status ) {
		wp_die( __( 'HTTP redirect status code must be a redirection code, 3xx.' ) );
	}

	$location = wp_sanitize_redirect( $location );

	if ( ! $is_IIS && 'cgi-fcgi' !== PHP_SAPI ) {
		status_header( $status ); // This causes problems on IIS and some FastCGI setups.
	}

	/**
	 * Filters the X-Redirect-By header.
	 *
	 * Allows applications to identify themselves when they're doing a redirect.
	 *
	 * @since 5.1.0
	 *
	 * @param string|false $x_redirect_by The application doing the redirect or false to omit the header.
	 * @param int          $status        Status code to use.
	 * @param string       $location      The path to redirect to.
	 */
	$x_redirect_by = apply_filters( 'x_redirect_by', $x_redirect_by, $status, $location );
	if ( is_string( $x_redirect_by ) ) {
		header( "X-Redirect-By: $x_redirect_by" );
	}

	header( "Location: $location", true, $status );

	return true;
}

Hooks

apply_filters( ‘wp_redirect’, string $location, int $status )

Filters the redirect location.

apply_filters( ‘wp_redirect_status’, int $status, string $location )

Filters the redirect HTTP response status code to use.

apply_filters( ‘x_redirect_by’, string|false $x_redirect_by, int $status, string $location )

Filters the X-Redirect-By header.

Changelog

Version Description
5.4.0 On invalid status codes, wp_die() is called.
5.1.0 The $x_redirect_by parameter was added.
1.5.1 Introduced.

User Contributed Notes

  1. Skip to note 7 content

    wp_redirect() does not validate that the $location is a reference to the current host. This means that this function is vulnerable to open redirects if you pass it a $location supplied by the user. For this reason, it is best practice to always use wp_safe_redirect() instead, since it will use wp_validate_redirect() to ensure that the $location refers to the current host. Only use wp_redirect() when you are specifically trying to redirect to another site, and then you can hard-code the URL.

    // We don't know for sure whether this is a URL for this site,
    // so we use wp_safe_redirect() to avoid an open redirect.
    wp_safe_redirect( $url );
    
    // We are trying to redirect to another site, using a hard-coded URL.
    wp_redirect( 'https://example.com/some/page' );

  2. Skip to note 9 content

    Unless this is patched to perform this natively in the future, be sure to include nocache_headers(); before the wp_redirect if you want to make sure the visitor’s browser doesn’t cache the redirect page result (can even happen when this is set to use a 302 redirect) which may cause the redirect to happen for longer than desired.

    For example, this can be problematic when used to redirect to a login page when trying to access protected content since the visitor can then log in to find that they’re still taken back to the login page when trying to go back to that page they were trying to go to due to the redirect having been potentially cached by their web browser (again, even with it being a 302 redirect.) Having nocache_headers(); before the redirect prevents this potential issue.

  3. Skip to note 11 content

    /**
     * Redirect categories, tags, date, author and specific custom taxonomies to homepage
     */
    function my_redirect_taxonomy_archive() {
        // redirect category, tag, date, author archives
    	if (
    		is_category() ||
    		is_tag() ||
    		is_date() ||
    		is_author()
    	){
    		wp_redirect( home_url(), 301 );
    	} else if ( is_tax() ) { // redirect custom taxonomy term archives
    		$archive_taxonomies_to_redirect = [
    			'book',
    			'event',
    		];
    
    		foreach($archive_taxonomies_to_redirect as $taxonomy) {
    			if ( is_tax( $taxonomy ) ) {
    				wp_redirect( home_url(), 301 );
    			}
    		}
    	}
    }
    add_action( 'template_redirect', 'my_redirect_taxonomy_archive' );

  4. Skip to note 12 content

    get_permalink() is only really useful for single pages and posts, and only works inside the loop.

    WP Redirect to Current Page

    global $wp;
    wp_redirect( get_permalink( home_url( $wp->request ) ) );