WordPress custom post query last page 404 problem
In the development of WordPress custom query logic, when the number of articles per page of the custom post query page is less than the number of articles per page set in the background, there is often a problem that the last page is 404. This is because in this case, the logic of the paging calculation precedes the query to get the articles, and, in fact, there are articles on the last page, but they just aren't displayed.
To solve this problem, we just need to set the number of articles per page before fetching them again, to do this, use the pre_get_posts hook, see the code below.
add_action('pre_get_posts', function ($query)
{
if ( ! is_admin() && $query->is_tax('book_cat')) {
$query->set('posts_per_page', 12);
}
});
pre_get_posts The main function of this Hook is to provide us with an opportunity to modify the query object after creating the query variable object and before running the actual query to modify the query variable. We can use this Hook to modify the paging query parameters, and set the number of articles displayed on each page in the article query to the number of paging we need.
Besides the paging problem, other similar problems can be modified by applying this hook.