WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress Change Default Number of Displayed Posts


By default, WordPress displays the same number of posts for the home page (when it is set to display posts) and all types of archive views. To change the default number of posts displayed for any specific view, you can add this simple function to your theme’s functions.php file.

Here we have defined a function named shapeSpace_number_displayed_posts that hooks into WordPress at the pre_get_posts hook. Inside the function, we first check to make sure that the query is the main, non-admin query. If it is, then the function continues with a check for is_search(), which is a conditional tag that returns true if the current query is a search query. If it is a search query, then we use the set() method to change the value of posts_per_page to 10.

I use this technique to customize the number of posts displayed for various archive views over at htaccessbook.com. To use for your own site, include the entire slab of code in your theme’s functions file and done.

Of course, it is possible to change the conditional tag to something other than is_search() should you want to customize the number of posts for some other type of query. Here is an example where we change the number of posts displayed for the archive view of a Custom Post Type named forum:

This is the exact same code with the exception of the conditional tag, which now is is_post_type_archive(). As you can imagine, hooking into pre_get_posts like this opens the doors to endless ways that we can customize our WordPress queries. Here is a list of WordPress Conditional Tags to give you some ideas.

Learn more

WordPress Themes In Depth

Show Support

Like our new Facebook Page to show support!