Focus Your WordPress Front Page and Awesomize Your Archives with Various Post Counts

Focus Your WordPress Front Page and Awesomize Your Archives with Various Post Counts

WordPress makes it easy to control the number of posts you show at a time on your site.

All you need to do is go to the Reading panel under Settings and control the number there.

The problem is that whatever number you put in that spot will apply to your whole site. So if you wanted 5 posts on your homepage, for example, but 10 posts on your category pages, you couldn’t do it.

There is a workaround, however. And so that’s what we’ll go over below.

featured-number-posts-control

Code for Your Functions File

The code below should go into your functions.php file. (Appearance > Editor > Theme Functions – functions.php.)

As you’ll be changing your theme, you should probably consider either creating a child theme.

We’ll start by showing the code for controlling the number of posts on the home page, and then we’ll build out from there, and you’ll get the idea for how to control other pages.

Here’s code to have only 3 posts show up on the homepage.

 function hwl_home_pagesize( $query ) {
 if ( is_admin() || ! $query->is_main_query() )
 return;
 if ( is_home() ) {
 // Display only 3 posts
 $query->set( 'posts_per_page', 3 );
 return;
 }
 }
 add_action( 'pre_get_posts', 'hwl_home_pagesize', 1 );

Next, I’ll add showing 5 posts on the category pages. You’ll notice I’ve just put a few more lines of code above the final curly bracket.

 function hwl_home_pagesize( $query ) {
 if ( is_admin() || ! $query->is_main_query() )
 return;
 if ( is_home() ) {
 // Display only 3 posts
 $query->set( 'posts_per_page', 3 );
 return;
 }
 if ( is_archive() ) {
 // Display only 5 posts
 $query->set( 'posts_per_page', 5 );
 return;
 }
 }
 add_action( 'pre_get_posts', 'hwl_home_pagesize', 1 );

Next, I’ll showing only 2 post in category with the ID 3. You can either put the category ID between the quotation marks, or your can put the category slug name. (If you aren’t sure how to find category IDs, you can see how to do that here.)

 function hwl_home_pagesize( $query ) {
 if ( is_admin() || ! $query->is_main_query() )
 return;
 if ( is_home() ) {
 // Display only 3 posts
 $query->set( 'posts_per_page', 3 );
 return;
 }
 if ( is_category( '3' ) ) {
 // Display only 2 posts
 $query->set( 'posts_per_page', 2 );
 return;
 }
 if ( is_archive() ) {
 // Display only 5 posts
 $query->set( 'posts_per_page', 5 );
 return;
 }
 }
 add_action( 'pre_get_posts', 'hwl_home_pagesize', 1 );

One important note: Because I already have all the categories set to 5 posts, I’m going to make sure the code for this individual category is placed before the code for all the categories.

As you can see, you can go on like this, controlling other pages too, such as search pages or other category pages. You can find more potential tags here. And you can read up on the basic code in general here.