Scenario: Settings > Reading set to show 10 (or whatever number, doesn’t matter) latest blog posts (WordPress default).
And you want to display just 3 Posts without links to next sets of paginated pages.
So let’s just add this in functions.php:
add_action( 'pre_get_posts', 'be_change_home_posts_per_page' );
/**
* Change Posts Per Page for Posts page
*
* @author Bill Erickson
* @link http://www.billerickson.net/customize-the-wordpress-query/
* @param object $query data
*
*/
function be_change_home_posts_per_page( $query ) {
if( $query->is_main_query() && !is_admin() && is_home() ) {
$query->set( 'posts_per_page', '3' );
}
}
Simple, right?
Apparently, that is not sufficient. When you reload your Posts page (the front page or the homepage, in this case) you’ll find that while only 3 Posts are displayed, pagination will continue to appear.
By setting no_found_rows
to true, we can truly retrieve a fixed number of posts thus getting rid of the pagination.
add_action( 'pre_get_posts', 'be_change_home_posts_per_page' );
/**
* Change Posts Per Page for Posts page
*
* @author Bill Erickson
* @link http://www.billerickson.net/customize-the-wordpress-query/
* @param object $query data
*
*/
function be_change_home_posts_per_page( $query ) {
if( $query->is_main_query() && !is_admin() && is_home() ) {
$query->set( 'posts_per_page', '3' );
$query->set( 'no_found_rows', true );
}
}