WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a way to show a 404 page if the current logged in user does not have the right clearance to view the page? I am looking for a PHP method, something like

if( !current_user_can('administrator') ) { show_404(); exit(); }

I have thought about using a redirect, but I would like to keep the url the same.

share|improve this question
If you are denying access to a user for a page which exists, 404 is the wrong error code to use. A 401 or 403 would make more sense. – moopet Jul 12 '13 at 9:18
You are right. I was under the impression from the client that he did not want anyone without access to even know the page existed, throwing a 401 would say it exists but prohibited. Nonetheless, it would be an easy change to throw a 401 instead. – imHavoc Jul 12 '13 at 19:11
up vote 28 down vote accepted

I was able to display a 404 error by using the following code in my header.

  global $wp_query;
  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

share|improve this answer
very good answer – seron Sep 14 '13 at 20:03

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 );

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.

share|improve this answer
I have thought about using this. But a couple downfalls that I see is that two 404 templates would have to be created and maintained (page and real). The client would have to create a 404 page. And I would like to keep the URL the same. Example, if I go to example.com/restricted, I would not be redirected to .../404/ – imHavoc Aug 4 '11 at 7:02
Actually I just realized that the 404.php is the template. My mistake. – imHavoc Aug 4 '11 at 7:24

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.