How can you show all posts on a archive page for a specific custom post type (No Posts Pagination)

How can you show all posts on a archive page for a specific custom post type (No Posts Pagination)

Sometimes we need to show all of the published custom posts of a specific custom post type on it’s archive page that should not have a posts pagination

That means, if you have a custom post type “Portfolio” with slug ‘portfolio’, and you want to show all of the published “Portfolio” post types in the archive page (for example, archive-portfolio.php)) and don’t want to use post pagination, then you can just follow the below procedure:

Open your functions.php file and write down the below code:

function codexin_portfolio_post_type( $query ) {
    if ( is_post_type_archive( 'portfolio' ) ) {
        $query->set( 'posts_per_page', -1 );
        return;
    }
}
add_action( 'pre_get_posts', 'codexin_portfolio_post_type', 1 );

And you will get the required results. You can always replace the slug ‘portflio’ with your own custom post type slug in the above code.

Here, we are using a WP hook pre_get_posts to filter the $query object. You can see as per https://codex.wordpress.org,

This hook is called after the query variable object is created, but before the actual query is run.

The pre_get_posts action gives developers access to the $query object by reference (any changes you make to $query are made directly to the original object – no return value is necessary).

The last parameter in the above hook is the priority. We set the priority as ‘1’, so that the function ‘codexin_portfolio_post_type’ executes at the first of that hook action.

For full references, please visit here

Leave a Comment