maybe_redirect_404()
云策文档标注
概述
maybe_redirect_404() 函数用于在定义 NOBLOGREDIRECT 常量时,纠正主站点的 404 重定向。它检查条件并应用过滤器来重定向到指定 URL。
关键要点
- 函数仅在主站点且为 404 状态,同时定义了 NOBLOGREDIRECT 常量时执行。
- 使用 blog_redirect_404 过滤器允许自定义重定向 URL。
- 如果 NOBLOGREDIRECT 设置为 '%siteurl%',则重定向到网络首页 URL。
- 重定向后调用 exit 终止脚本执行。
代码示例
function maybe_redirect_404() {
if ( is_main_site() && is_404() && defined( 'NOBLOGREDIRECT' ) ) {
$destination = apply_filters( 'blog_redirect_404', NOBLOGREDIRECT );
if ( $destination ) {
if ( '%siteurl%' === $destination ) {
$destination = network_home_url();
}
wp_redirect( $destination );
exit;
}
}
}注意事项
- 确保 NOBLOGREDIRECT 常量在 WordPress 配置中正确定义,否则函数不会触发。
- 使用 blog_redirect_404 过滤器时,需注意参数为 NOBLOGREDIRECT 的值,可用于动态调整重定向目标。
- 重定向操作使用 wp_redirect(),需确保在输出任何内容前调用,以避免 headers already sent 错误。
原文内容
Corrects 404 redirects when NOBLOGREDIRECT is defined.
Source
function maybe_redirect_404() {
if ( is_main_site() && is_404() && defined( 'NOBLOGREDIRECT' ) ) {
/**
* Filters the redirect URL for 404s on the main site.
*
* The filter is only evaluated if the NOBLOGREDIRECT constant is defined.
*
* @since 3.0.0
*
* @param string $no_blog_redirect The redirect URL defined in NOBLOGREDIRECT.
*/
$destination = apply_filters( 'blog_redirect_404', NOBLOGREDIRECT );
if ( $destination ) {
if ( '%siteurl%' === $destination ) {
$destination = network_home_url();
}
wp_redirect( $destination );
exit;
}
}
}
Hooks
- apply_filters( ‘blog_redirect_404’, string $no_blog_redirect )
-
Filters the redirect URL for 404s on the main site.
Changelog
| Version | Description |
|---|---|
| MU (3.0.0) | Introduced. |