4

On a date archive page when no posts exist (for that date) WordPress throws across to the 404 page.

Is there a way to make WordPress continue to use the original archive instead of the 404. That way I can use if ( have_posts() ) condition to output a "No posts found" message.

4

You can move the code from OP's answer into a 404 template filter and force WP to load the date.php file instead of 404.php. It'll still send the 404 header, but render the page with a different template.

function wpd_date_404_template( $template = '' ){
    global $wp_query;
    if( isset($wp_query->query['year'])
        || isset($wp_query->query['monthnum'])
        || isset($wp_query->query['day']) ){
            $template = locate_template( 'date.php', false );
    }
    return $template;
}
add_filter( '404_template', 'wpd_date_404_template' );
3

Okay, on reflection I'm not sure if I'm asking too much of WP. I guess from an SEO point of view I do want empty pages to 404, I certainly don't want them indexed.

I decided instead to use the 404 template to output the "No posts found" message, but because the functions is_date(), is_day() (et al) will not work on the 404 page I added this code to detect if the 404 was meant to be a date archive.

Paste the following into your 404.php to detect the URL:

global $wp_query;

$is_date_archive = ( isset($wp_query->query['year']) || isset($wp_query->query['monthnum']) || isset($wp_query->query['day']) );

I can then use the variable $is_date_archive to modify the 404 template accordingly.

Example (404.php)

global $wp_query;

$is_date_archive = ( isset($wp_query->query['year']) || isset($wp_query->query['monthnum']) || isset($wp_query->query['day']) );

if( $is_date_archive ){ echo 'No posts found'; } else { echo 'general 404 page'; }

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.