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.

If you have an index.php with a loop such as:

if(have_posts()){
    while(have_posts()){
        the_post();
    }
}

And nothing is returned, you would generally do a:

if(have_posts()){
    while(have_posts()){
        the_post();
    }
}else{
    //display message
}

However, what if you have a 404.php? Will that page be displayed if nothing is returned in terms of the loop (assuming I have not written the else part of the loop)?

share|improve this question

2 Answers 2

up vote 0 down vote accepted

If you want to force the 404.php template to load if there are no found posts, use the template_include filter:

function wpa84794_template_check( $template ) {
    global $wp_query;
    if ( 0 == $wp_query->found_posts ){
        $template = locate_template(
            array( '404.php', $template ),
            false
        );
    }
    return $template;
}
add_filter( 'template_include', 'wpa84794_template_check' );
share|improve this answer
    
This will only show the 404 page but will not return the 404 code. –  Mark Kaplun Feb 6 '13 at 19:13
    
@MarkKaplun - this is true, but the question didn't specify that requirement. it technically shouldn't return a 404 code anyway, since the URI may or may not contain posts depending on who is visiting the page. –  Milo Feb 6 '13 at 19:17
    
I agree, but not sure that kyle here even understands the distinction. Even this code, while technically correct might turn away people from the site if searching for something returns what looks like a 404 page. They might think the site is broken. –  Mark Kaplun Feb 6 '13 at 19:24
    
agreed, it's a strange thing to do and I wouldn't recommend it. –  Milo Feb 6 '13 at 19:35

Checkout the WordPress Template Hierarchy page, in particular the diagram: http://codex.wordpress.org/Template_Hierarchy#Visual_Overview

In short though the answer is no, the 404.php is only used when the URL does not resolve to any other template type.

share|improve this answer
    
thank you - is there a way to make it show? –  Kyle Adams Feb 6 '13 at 16:50
    
Yeah, try codex.wordpress.org/Function_Reference/get_template_part with something like <?php get_template_part( '404' ); ?> –  Alex Feb 6 '13 at 17:05

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.