問題描述
我需要根據條件強制 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。