404 Page error on WordPress Pagination in Custom Post Type

I have been dealing with this 404 page error on custom post type for few days. Like all of you who are reading this post and trying to get answer, I’ve been through dozen of solutions, but none of them really work for me.

The symptom

When you try to manipulate the code, show a custom number of posts_per_page, e.g. 8 posts on your blog page. You may experience 404 page error when you try to access any page other than the first page. The URL looks like this:

http://mysite.com/taxonomy/term/page/3

Possible Solutions

Solutions include:

  • use WP_Query() instead of Query_posts()
  • proper use get_query_var(‘paged’)
  • change Permalinks in settings
  • change to another pagination plugin

and there maybe more. If one of these solution happened to work for you, then stay happy. But chances are, the problem may come back and haunt you some day in the future if some conditions changed. Sometimes, the 404 page error comes back unexpected when total post reaches a certain number.

then what is the real cause and what is the solution?

The Problem

The problem is the WordPress posts_per_page. WordPress has only one setting for posts_per_page, it can be found at:

Admin > Settings > Reading

the setting is:

Blog pages show at most:     X posts

 

X is what WordPress actually stored in database to deal with pagination. Of course we can customize and change this by using “posts_per_page = Y” in our code, but it won’t work until WordPress reaches that part of code.

When dealing with pagination, WordPress reads X from database first. Once it passes this check, it then loads your code in, e.g. “taxonomy.php”, and query the posts by your setting “posts_per_page = Y”.

For example, there is 19 posts in total, and we want to show 8 (Y as reference) posts per page on the blog page. When posts_per_page = 8, there should be 3 pages. But WordPress doesn’t see it when we access it using “http://xxxxxx/xxx/page/3”, because there is only 2 pages base on the settings for “Blog pages show at most”, where says X =10 if you didn’t change it.

The Solution

Once you understand how WordPress works, the solution can be simple. Set the value X equals to Y. This will work perfectly when you have only one setting throughout the whole website, and it doesn’t matter your are working with standard post type or custom post types.

Under some circumstances,  you need to set multiple posts_per_page for different post types, make sure the X is no larger than the minimum posts_per_page among the settings.

Comments are closed.

Post Navigation