1

I need to override the 404 code for a very specific scenario and it's not yet fully working.

I am linking day archives with rel=prev/next, and the chain is supposed to be intact start-to-end. For this reason, at least one post needs to be published everyday, best right at midnight. This should not be a problem editorially, with at least 10 posts being expected even on a slow news day.

However, accidents may happen - like downtime or unwarranted deletions or whatnot. Even in these cases, things should be repaired from the publishing end as soon as noticed (with at least one post forth/backdated to cover for the empty day).

Still, I wouldn't want the prev/next chain to ever be broken, so I'm thinking this as the ultimate fallback - ideally never triggered.

I have added the following to the functions.php template:

add_action( 'template_redirect', 'empty_day', 0 );
function empty_day() {
    global $wp_query;
    if ($wp_query->post_count == 0 && $wp_query->query['day'] ) {
    status_header( '200' );
        $wp_query->is_404 = false;
        $wp_query->is_day = true;
        $wp_query->is_date = true;
        $wp_query->is_archive = true;
    }
}

It works nicely redirecting the empty page to the archive template, prev/next tags in place.

However, functions stop working outside the loop completely (no return), so I can't get_the_time nor get_the_date to output anything.

I already tried the solutions suggested here or here, but they still fail to get the date with the template_redirect filter or redirect the template altogether with 404_template.

Any Idea on how to have them working again?

1

The timing of relevant parts of the process is following:

  1. Query executes and fetches posts (or in this case no posts)
  2. template_redirect fires
  3. Template file is determined from query variables and loaded

When you change query variables in template_redirect you change template choice (which you observe), but you still have no posts in query.

The functions still work, they just don't have a post to work on.

It's quite a peculiar case, because which posts would you expect in an archive that is 404 and has no posts?

I am not sure without playing with such a setup but I would probably try to redirect "ahead" rather than "fake" valid page out of 404.

1

Got the job done by building a "private" time function to work with:

function my_date() { {
$day = get_query_var( 'day' );
$monthnum = get_query_var( 'monthnum' );
$year = get_query_var( 'year' );
$my_date = $year.'-'.$monthnum.'-'.$day;
} return $my_date; }

Now when I call this, it outputs fine.

  • Glad that you were able to solve your own question. Be sure to mark your answer as resolved in the next two days. – Ethan Jinks O'Sullivan Sep 1 '16 at 22:16

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.