Non existing blog pages are not redirected to 404

I’ve got a page called Blog. In the Settings -> Reading I’ve set my Blog page as Posts page. In the menu when I click on the Blog link the posts are loaded correctly and pagination works, so far so good. All the info is coming from the home.php template.

I’m using my own pagination code that generates the pages looking at max_num_pages and paged params. In short it generates correct amount of pages with the correct links.

However, when I test a non-existent blog page. For example there are 5 pages exist and I type blog/page/6 it doesn’t get redirected to 404, instead it seems to fall back to the else statement of the main if(have_posts()).

I’ve tested the category paginated pages that use the same pagination code, they work correctly: non existing category pages of type category/<category_name>/page/2 are redirected to 404 template.

I can’t think of anything why the main blog ‘paged pages’ that don’t exist won’t redirect to 404.

I would hugely appreciate any tips and help.

Many thanks,
Dasha

3 Answers
3

This is the default WordPress behaviour for pagination when using a custom query (where you feed in the paged value yourself) or in the index.php as it doesn’t realize there isn’t content to display on the XXXth page until it has already loaded the template, and then tries to run the WP_Query.

You can try adding logic that determines if $paged is set and no results are found, then throw the 404, which would look something like this:

header("HTTP/1.0 404 Not Found");
$wp_query->set_404();
require TEMPLATEPATH.'/404.php';
exit;

Leave a Comment