Number of pages – multiple (custom) post types

My archive query contains a custom posts_per_page, order, orderby, post_type and paged (via wp-pageNavi).

array (
    'order' => 'DESC',
    'orderby' => 'title',
    'paged' => 1,
    'post_type' => Array (
        'post',
        'cust_article',
    ),
    'posts_per_page' => 15,
);

My post_type contains ‘post’ and ‘cust_article’.

I have 1 ‘post’ and 65 ‘cust_article’.
posts_per_page is currently set to 5 in admin.

My problem is that the maximum amount of pages is limited by the amount of pages ‘post’ contains. Since I have only one ‘post’ the pages are limited to 1, even though I get all pages displayed (5 pages, posts_per_page set to 15), pages other than page 1 will return 404.

Creating a second ‘post’ and setting the posts_per_page to 1 allows access to the second page, following pages will also return 404.

I’m using the same query for my custom post_type archives, with a single post_type, adding a second to the query creates the same error.

I know that the paging is limited by the amount of posts and the set option posts_per_page. 5 ppp and 21 posts => maximum of 5 pages

By theory posts from 2 post_types should extend the post count. 5ppp and 21 posts + 12 posts => max 7 pages

1 Answer
1

Milo is right, you should be using pre_get_posts instead of calling a 2nd query on load. This will make paging much easier. Whatever the orderby session you’re using it should still be accessible in the hook. The code to do so is fairly straightforward too, it would look like this:

/**
 * Modify the query before it gets loaded
 *
 * @param WP_Query Object $query
 *
 * @return void
 */
function wpse_228230( $query ) {

    if( $query->is_admin ) {
        return;
    }

    // Your archive conditional here
    if( is_post_type_archive() ) {
        $query->set( 'post_type', array( 'post', 'cust_article' ) );
        $query->set( 'posts_per_page', 15 );
        $query->set( 'orderby', array( 'title' => 'DESC' ) );
    }

}
add_action( 'pre_get_posts', 'wpse_228230' );

This will modify the main query before it hits the database. Otherwise WordPress will get the natural query, hit your custom WP_Query and ping the database again which is unnecessary overhead.

Leave a Comment