How to Change the Default Number of Posts Displayed in WordPress

By default, WordPress displays the same number of posts for both the homepage (when configured to display blog posts) and all post archive types. In order to change the default number of displayed posts for a particular type of archive, you can add the following function to your theme’s functions.php file or to your WordPress site plugin:

function devise_number_displayed_posts($query) {
	if (is_admin() || !$query->is_main_query()) {
		return;
	}
	if (is_search()) {
		$query->set('posts_per_page', 10);
		return;
	}
}
add_action('pre_get_posts', 'devise_number_displayed_posts', 1);

In this code, we have defined a function called devise_number_displayed_posts that hooks the pre_get_posts hook into WordPress. Inside this function, we first check to make sure the request is primary and not non-admin. If this is true, then the function continues to check for the presence of is_search (). is_search (), in turn, is a conditional tag that returns true if the current request is a search request. If the query is a search query, then we use the set () method to change the posts_per_page value to 10.

Of course, you can change the conditional tag to something else for the week is_search () in order to adjust the number of records to display for a different type of query. Below we will give an example where we changed the number of displayed posts for an archive of a custom post type called forum:

function devise_number_displayed_posts($query) {
	if (is_admin() || !$query->is_main_query()) {
		return;
	}
	if (is_post_type_archive('forum')) {
		$query->set('posts_per_page', 10);
		return;
	}
}
add_action('pre_get_posts', 'devise_number_displayed_posts', 1);

This is the same code, except for the absence of the conditional tag, which is now replaced by is_post_type_archive ().

As you might have already imagined, intercepting pre_get_posts like the above opens the door to any way we can customize our WordPress queries.

Leave a Reply

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

Ads Blocker Image Powered by Code Help Pro
It looks like you\'re using an Adblock. That\'s okay. Who doesn\'t­čśö

But without advertising, we can\'t keep making this awesome.
Please disable Adblock for our domain­čÖĆ

Refresh