I'm trying to display the last 10 posts only on the home without wp creating /page/2, /page/3, archives.
I've been testing and it seems if you disable pagination it will just grab everything crashing the server. (Don't do this at home).
if ( !is_admin() && $query->is_home() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 10 );
$query->set( 'nopaging' , true );
}
Someone suggested " no_found_rows=true" that doesn't do it either.
Is this just impossible to do? It seems like it will either create the pages or show all, there's no way to "LIMIT" it?
I'm trying to display the last 10 posts only on the home without wp creating /page/2, /page/3, archives.
I've been testing and it seems if you disable pagination it will just grab everything crashing the server. (Don't do this at home).
if ( !is_admin() && $query->is_home() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 10 );
$query->set( 'nopaging' , true );
}
Someone suggested " no_found_rows=true" that doesn't do it either.
Is this just impossible to do? It seems like it will either create the pages or show all, there's no way to "LIMIT" it?
If you want to prevent the API from generating pagination links, you can use the found_posts
filter to make WordPress think there are never more than 10 posts returned from the current query.
add_filter( 'found_posts', 'wpd_disable_home_pagination', 10, 2 );
function wpd_disable_home_pagination( $found_posts, $query ) {
if ( !is_admin() && $query->is_home() && $query->is_main_query() && $found_posts > 10 ) {
return 10;
}
return $found_posts;
}
EDIT-
You could redirect any paginated URL:
add_action( 'pre_get_posts', 'wpd_redirect_pagination_urls', 10, 2 );
function wpd_redirect_pagination_urls( $query ) {
if ( !is_admin() && $query->is_home() && $query->is_main_query() && $query->is_paged() ) {
wp_redirect( get_post_type_archive_link( 'post' ) );
exit;
}
}
This is a mistake it will retrieve of posts:
$query->set( 'nopaging' , true );
What you should do instead is:
if ( !is_admin() && $query->is_home() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 10 );
$query->set( 'paged', '1'); // Makes /page/2/, etc links redirect to home
$query->set( 'no_found_rows', true ); // Avoid counting rows, faster processing.
}
If your theme is still rendering the navigation buttons you'll have to add some logic to hide them on the pages you disabled pagination, for me it was the home page:
if (!is_home()) {
// show pagination buttons
}
The nopaging
parameter is used to show all posts or use pagination (https://codex.wordpress/Class_Reference/WP_Query#Pagination_Parameters). Default value is 'false'
: use paging. So it is expected behaviour when you set it to true, the sky comes falling down (if you have a big number of posts that is).
By using only the posts_per_page
parameter, the query will grab the number of posts you tell it to and that will be that.