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.

Can someone tell me how to direct a user to the main 404 file instead of having to print an error message saying "file not found" in single.php?

For example:

<?php

if (!$myVar) {
  // go to 404.php and return an official file not found header
} else {
  // show the following HTML
}

?>
share|improve this question
    
You want to just direct all logged in users not named "Mike" to a 404 page? –  Wyck Dec 6 '12 at 22:41
    
That was just a basic example, but what I'd like to do is send the user to the 404.php page if a certain condition is not met. –  user1462 Dec 6 '12 at 22:42
    
I know, what about users not logged in? –  Wyck Dec 6 '12 at 22:43
    
It's for users who are not logged in. –  user1462 Dec 6 '12 at 22:51
1  
The please reword your question to say so, it is too confusing in its current form. –  Wyck Dec 6 '12 at 22:55

1 Answer 1

up vote 2 down vote accepted

You can use the locate_template() function to include the 404 template. Remember to do this instead of using get_header() or generating any output; otherwise you will have a duplicate.

<?php

if ( ! $myVar ) {
    status_header(404);

    global $wp_query;
    $wp_query->is_404 = true;

    locate_template('404');
    return;
}

// otherwise, show the following HTML
share|improve this answer
1  
Or just use locate_template(); return;. –  toscho Dec 6 '12 at 22:59
    
Thanks, I was just about to improve the answer –  bungeshea Dec 6 '12 at 23:00
    
I tried your code, but nothing's appearing where that function and return is. Am I missing something? I just have a file named 404.php in my theme directory. I would like it to redirect to this page so it includes File Not Found in the title element, body, etc. –  user1462 Dec 6 '12 at 23:02
3  
Did you log out..? –  Wyck Dec 6 '12 at 23:04
    
I've updated my original code example above. It just checks if a variable is false and if so, should send the user to the 404. Sorry for the confusion about being logged in or not. –  user1462 Dec 6 '12 at 23:06

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.