Wordpress - Redirect Restricted Page to 404
I was able to display a 404 error by using the following code in my header.
<?php
global $wp_query;
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 ); exit();
?>
To break it down:
$wp_query->set_404()
: tells the wp_query this is a 404, this changes the title
status_header()
: sends a HTTP 404 header
get_template_part()
: displays the 404 template
Why don't you create a page that show error message and then redirect user to that page? Here is a simple way to achieve that:
Open the 404.php
file and add these lines to the top of it:
/**
* Template Name: 404 Page
*/
Create a page with 404 Page
template. Then redirect users:
if ( !current_user_can('administrator') ) {
$404_page = get_permalink( $404_page_id );
wp_redirect( $404_page );
exit();
}
The reason you should use a page for 404 request is: in WP 404 page actually is a page that doesn't exists, WP has to search for all of its content before returning the 404 page and that work is a waste of resource. Using a pre-configured page that might help you run your blog faster.