How to Overwrite Number of Posts on Custom Post Types Archive Page

WordPress has an option to allow you to choose number of post to be displayed in your site. This option can be seen from Writing settings page.

number of post

The number you set here is the number of post that will be displayed on all archive pages, including the archive page for Custom Post Type (CPT). However, there’s a way to overwrite this number of post to be displayed on your CPT archive page.

1 2 3 4 5 6 7 8 9 10 11 12 13
<?php
//* Overwrite number of posts in CPT archive page
if ( !is_admin() ) {
add_filter( 'pre_get_posts', 'afn_cpt_posts_per_page' );
}
function afn_cpt_posts_per_page( $query ) {
if ( $query->query_vars['post_type'] == 'portfolio' ) $query->query_vars['posts_per_page'] = 6;
return $query;
}
view raw functions.php hosted with ❤ by GitHub

This code should go into functions.php file of your child theme. The code is self-explanatory. We use pre_get_posts filter to overwrite the number of post in portfolio post type. Simply replace 'portfolio' with the name of your CPT.

If you’re new to CPT, here are some great tutorials we’ve published about CPT:

  1. Creating Your First Custom Post Type
  2. Custom Post Type Code Generator
  3. Adding Custom Post Types to Main Feed
  4. Switch Post to Custom Post Type or Vice Versa

Leave a Reply

Your email address will not be published. Required fields are marked *