Wordpress - How to force a 404 on WordPress
You could try the Wordpress function status_header()
to add the HTTP/1.1 404 Not Found
header;
So your Code 2 example would be:
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' );
This function is for example used in this part:
function handle_404() {
...cut...
// Guess it's time to 404.
$wp_query->set_404();
status_header( 404 );
nocache_headers();
...cut...
}
from the wp
class in /wp-includes/class-wp.php
.
So try using this modified Code 2 example in addition to your template_include
code.
This code worked for me:
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(); } }
I wouldn't recommend forcing a 404.
If you're worried about search engines why not just do a "no-index,no-follow" meta on those pages and block it with robots.txt?
This may be a better way to block the content from being viewed
add_filter( 'template_include', 'nifty_block_content', 99 );
function nifty_block_content( $template ) {
if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
$template = locate_template( array( 'nifty-block-content.php' ) );
}
return $template;
}
You could probably also use this method to load 404.php
but I feel that using a page template might be a better option.
source