Milan Latinović
Software Engineer and Enterprise Architect
WordPress archive post limit: with example
If you are having a personal or company blog, most likely you keep some kind of archive, with the possibility to configure the WordPress archive post limit.
Table of Contents
Why is WordPress archive post limit important?
Let us talk about the chronological nature of blogging. This means that great articles can get lost in your archives.
Therefore, creating an archives section and placing it within a search bar and an archives widget in your sidebar can make it easier for visitors to search through your older content.
You should limit the number of posts on the archive page when the default setting is not a good choice. Furthermore, it’s important to set a limit to the number of posts on Archive pages. Furthermore, your visitors and their expectations should influence this decision.
Code sample
You can do this by 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 for a limit the number of posts on the archive page explains to WordPress that if $query (user action)
is archive.
In that case WordPress should set attribute called posts_per_page to 3
.
Also, after changes to the global $query
attribute, WordPress will continue with further processing.
Note: Making changes to archive.php template can be very important, and here is a reason for that.
Secondly, 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 templates), the mechanism will resolve to archive.php, and all settings we create for archive.php will be applied to the author, category, archive, taxonomy, date, and tag.
Furthermore, when making any kind of changes to your website, make sure to use the GIT repository and to do a proper code review.
Finally, In most cases, templates have at least category.php, but it’s always good to have a fallback template, such as archive.php parent template.