How to Limit Number Of Posts on Archive Pages

Sometimes, when creating a WordPress theme or customizing existing one, it’s important to set limit to number of posts on Archive pages.

This can easily be done with inserting small code snippet to functions.php file, as follows:

 /*
* This is a function which limits Number of Posts on Archive Pages
* For our web site, desired limit is 3
*/
function number_of_posts_on_archive($query){
if ($query->is_archive) {
$query->set('posts_per_page', 3);
}
return $query;
}
add_filter('pre_get_posts', 'number_of_posts_on_archive');

This code part explains to WordPress that if $query (user action) is archive, in that case WordPress should set attribute called posts_per_page to 3. After changes to global $query attribute, this should be returned to WordPress for further processing.

Note: Making changes to archive.php template can be very important, and here is a reason for that.

According to WordPress template hierarchy, archive.php template is parent of these templates:

  • author.php
  • category.php
  • archive-$posttype.php
  • taxonomy.php
  • date.php
  • tag.php

This means, that (if our template has none of these child template), mechanism will resolve to archive.php, and all settings we create for archive.php will be applied to author, category, archive, taxonomy, date and tag.

In most cases, templates have at least category.php , but it’s always good to have fallback template, such as archive.php parent template.

careveloper

We are educational service which provides resources to help you manage your digital service. Here you will find resources about WordPress development, how to build up your own web site weather it is a simple blog or advanced e-commerce web site.

Leave a Reply

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