I am trying to make it so when a regular user enters a place they shouldn't be, then they should be redirected to the 404 page, but the url must remain the same, as if they have entered an invalid address, so there is no way to know by looking at the address bar that the user has stumbled upon an admin page.

Since the redirect shouldn't happen always it can't be done though .htaccess and currently allow_url_include is disabled and I've read that it's strongly recommended that it should remain that way so I can't use include() with an exit.

update1: require() and require_once() appear to work, but they still add a / at the end of the URL.

  • I cannot think of url that will be 404... every page, for ex. mysite.com/some_extra/not/existing will be looking for page and if not found will echo Page not found not 404...
    – Maikal
    Sep 9, 2015 at 16:45
  • regular user enters a place they shouldn't be how does the system decide that?
    – Ejaz
    Sep 9, 2015 at 18:23
  • @Ejay if(!current_user_can('update_core')){ redirect_code_goes_here }
    – Nadroev
    Sep 9, 2015 at 18:45

1 Answer 1


You can try to use the template_redirect hook to check your conditions and then set the wp_query->is_404 variable, like below:

function wpse202198_set_404(){
      global $post;
      global $wp_query;
      if( $post->ID == PAGE_ID_OF_PROTECTED_PAGE ){
           $wp_query->is_404 = true;
add_action( 'template_redirect', 'wpse202198_set_404' );
  • Tried copying this (and replacing PAGE_ID_OF_PROTECTED_PAGE with the actual ID of course) at the beginning of the game without adding any other conditions and it doesn't trigger at all.
    – Nadroev
    Sep 9, 2015 at 18:08
  • Not sure I understand what you mean by at the beginning of the game but I guess I should have mentioned that this should go in your theme functions.php file Sep 9, 2015 at 18:25
  • I meant "page". I see no difference between putting this at the beginning of the page, after the header has been called, or in functions.php
    – Nadroev
    Sep 9, 2015 at 18:44
  • @Nadroev a template redirect hook will never trigger in a template file, because it runs before the template is loaded. that's why it must go in functions.php, or a plugin.
    – Milo
    Sep 9, 2015 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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