0

I'm using a custom WP_Query. The code is something like below:

$portfolio_args = array(
    'post_type'           => 'portfolio',
    'posts_per_page'      => 5,
    'paged'               => get_query_var( 'page' )
);

$portfolio_query = new WP_Query($portfolio_args);

Now, my portfolio post type has 15 entries (thus it is good for 3 pages). I can navigate to all these pages, but the issue is even the pages which does not have any portfolio entry (e.g. /page/4/, /page/5, ...) loads just fine (i.e. throws 200 in response header), whereas, I'm expecting it to throw a 404 error if the page has not any entry.

Is it the expected behaviour for custom query pagination? If so do I need to force a 404 response header somehow?

1 Answer 1

2

Response is based on the results of the main query. The decision is made before the template is loaded, which is how WP is able to serve a 404 template in the case of a 404.

As you've learned, the page post type lets you paginate endlessly in both the format pagename/page/n/, as well as the singular pattern pagename/n/. To generate a 404 for a different query, you'd need to hook something like template_redirect to check if your custom query contains posts so you can force a 404 before output starts.

The preferred solution is to set the has_archive argument for your custom post type, which enables an archive page. The main query will then be your collection of portfolio posts, and pagination will work as expected.

2
  • So, will I have access to '$portfolio_query' object in 'template_redirect' hook? Any example of using this hook for forcing a 404 error. Moreover, I cannot use 'archive-portfolio.php' method, it is limiting in some other aspects. Commented Jul 2, 2017 at 0:47
  • You'll have to create the query within the hooked function. See this answer for setting a 404.
    – Milo
    Commented Jul 2, 2017 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.