Redirect Restricted Page to 404

Question

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.

in progress 0
, Evan Yeung 10 years 2011-08-04T01:01:43-05:00 0 Answer 70 views 0

Answer ( 1 )

    0
    2021-08-06T03:08:56-05:00

    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

Leave an answer

Browse
Browse