问题描述
我需要根据条件强制 404 上一些帖子。我设法做到这一点 (虽然我不知道我是否做了正确的方法),而我正在让我的 404.php
模板按预期加载。
我的代码:
function rr_404_my_event() {
global $post;
if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
include( get_query_template( '404' ) );
exit; # so that the normal page isn't loaded after the 404 page
}
}
add_action( 'template_redirect', 'rr_404_my_event', 1 );
代码 2 来自 this related question – 同样的问题:
function rr_404_my_event() {
global $post;
if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
global $wp_query;
$wp_query->set_404();
}
}
add_action( 'wp', 'rr_404_my_event' );
我的问题:
虽然看起来不错,但如果我查看网络标签,我将获得状态 200 OK
。由于它是一个状态 200
,恐怕搜索引擎也可能索引这些页面。
预期行为:
我想要发送一个状态 404 Not Found
。
最佳解决方案
您可以尝试使用 WordPress 功能 status_header()
来添加 HTTP/1.1 404 Not Found
标题;
所以你的代码 2 的例子是:
function rr_404_my_event() {
global $post;
if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
global $wp_query;
$wp_query->set_404();
status_header(404);
}
}
add_action( 'wp', 'rr_404_my_event' );
此功能用于本部分:
function handle_404() {
...cut...
// Guess it's time to 404.
$wp_query->set_404();
status_header( 404 );
nocache_headers();
...cut...
}
来自/wp-includes/class-wp.php
的 wp
类。
所以,除了 template_include
代码之外,请尝试使用此修改的代码 2 示例。
次佳解决方案
这段代码对我有用:
add_action( 'wp', 'force_404' );
function force_404() {
global $wp_query; //$posts (if required)
if(is_page()){ // your condition
status_header( 404 );
nocache_headers();
include( get_query_template( '404' ) );
die();
}
}
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。