Redirect Restricted Page to 404

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.


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

Leave a Comment