WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] redirecting to 404.php from inside loop. (3 posts)

  1. isho
    Member
    Posted 6 years ago #

    I've run into a problem that I can't figure out the best way to solve.

    I have a 404.php page with a customized message. This page works fine for 404 and other server errors, but if the user links to a "post" or "page" that does not exist. The web server doesn't throw an error. Instead it goes to the loop with in index.php of my theme which then finds nothing to display and prints out a different message.

    Rather than recreate the code for 404.php with in index.php I'd like to redirect the user to 404.php. But you can't do this easily with php because content has already been output at this point, so php won't let you modify the headers.

    Has anyone out there come up with a good solution to this?

    Thanks in advance,
    Ishmael

  2. isho
    Member
    Posted 6 years ago #

    I think I figured it out.

    I added this code to the beginning of index.php.

    <?php
    if ( ! have_posts() ) {
    $url = get_option('siteurl') . '/index.php?error=404';
    wp_redirect ( $url );
    }
    ?>

  3. isho
    Member
    Posted 6 years ago #

    I added an is_search() check so that it handles empty search results.

    <?php
    if ( ! have_posts() && ! is_search() ) {
    $url = get_option('siteurl') . '/index.php?error=404';
    wp_redirect ( $url );
    }
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic