Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

2 Answers 2

up vote 17 down vote accepted

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

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

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

 
discard

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.