search ]

Change the Number of Posts Displayed on a CPT Archive Pages

In order to change the number of posts displayed on archive pages of a specific custom content type, you can use the pre_get_posts action, which you might already be familiar with.

By default, the number of posts displayed is determined by the settings in the WordPress admin dashboard under Settings > Reading under the option “Blog pages show at most”. However, you might want a different number of posts to be displayed on standard posts compared to custom content type posts that you’ve created yourself or through a plugin.

The pre_get_posts action acts as a filter for the main query running on the page. If you want to modify the number of results in this query, it’s better and more efficient to use pre_get_posts rather than creating a new query using WP_Query. Here’s the code you can use to achieve this:

// Display all posts on XXXXXX Archive Page
function sv_cpt_page( $query ) {
    if ( !is_admin() && $query->is_main_query() && is_post_type_archive( 'XXXXXXX' ) ) {
        $query->set( 'posts_per_page', '-1' );
    }
}
add_action( 'pre_get_posts', 'sv_cpt_page' ); 

Please note that you should replace XXXXXX with the name of the Custom Post Type you’ve defined.

In this case, all posts on the archive page of the XXXXXX content type will be displayed, as we’ve set posts_per_page to -1. You can change this to any number you prefer.
Similarly, if you want to do this for a specific taxonomy, you can do so as follows:

// Display all posts on XXXXXX tax Page
function sv_tax_page( $query ) {
    if ( !is_admin() && $query->is_main_query() && is_tax('project_category') ) {
        $query->set( 'posts_per_page', '-1' );
    }
}
add_action( 'pre_get_posts', 'sv_tax_page' );

In both cases, the use of !is_admin is to avoid affecting the WordPress admin interface. Using $query->is_main_query ensures that no other queries are affected by this setting.

You can use this method to change other parameters for the same query as well. Here are a few examples:

$query->set( 'orderby', 'title' );
$query->set( 'order', 'DSC' );
$query->set( 'post__not_in', array(7,11) ); // Exclude Posts
$query->set( 'cat', '-1,-1257' ); // Exclude Categories
$query->set( 'cat', '153' ); // Include Categories

Feel free to refer to the Codex for various values for these parameters.

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development