Sometimes we need to show all of the published custom posts of a specific custom post type on its 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 cdxn_portfolio_post_type( $query ) {
if ( is_post_type_archive( 'portfolio' ) ) {
$query->set( 'posts_per_page', -1 );
return;
}
}
add_action( 'pre_get_posts', 'cdxn_portfolio_post_type', 1 );
And you will get the required results. You can always replace the slug ‘portfolio’ 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://developer.wordpress.org/reference/hooks/pre_get_posts/
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 ‘cdxn_portfolio_post_type’ executes at the first of that hook action.
We hope this tutorial was helpful and easy for you. If you would like to read some more tutorials, you are welcome to visit our WordPress blog page.
Thank you.