0

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)?

0

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' );
4
  • This will only show the 404 page but will not return the 404 code. 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. 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
2

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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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