Archived topic
Limit the number of post
15 replies · Started by vidueiro on June 2, 2020
Hi
How Can I limit the number of post on the category? For default appear 10 categories, but when I want use 3 columns the last file appear alone. I would like I can use for example only 9 post.
Thanks
Regards
Hi there,
you can use a PHP snippet like this to change the posts per page for a specific category:
add_action('pre_get_posts', 'custom_posts_per_page');
function custom_posts_per_page($query) {
if (is_category( 'category-slug' );) {
$query->set('posts_per_page', 10);
}
}
But, I would like use in home page, the homepage use all categories and all cateogries. How can I add this code? With hook of elements?
On the home page, you could do this:
add_action( 'pre_get_posts', function( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( is_home() ) {
$query->set( 'posts_per_page', 9 );
}
} );
The code can be added like this: https://docs.generatepress.com/article/adding-php/
Now perfect, thanks!!
You're welcome :)
A last question, how can I change the number of the posts in a category? The before code and the plugin code snippet don't run.
Hi there,
you can use the is_category() conditional tag:
https://developer.wordpress.org/reference/functions/is_category/
add_action( 'pre_get_posts', function( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( is_home() ) {
$query->set( 'posts_per_page', 9 );
}
if ( is_category('your-category-slug') ) {
$query->set( 'posts_per_page', 9 );
}
} );
yes, ok, but how I do add this code? so that remove when update the theme, can I use any plugin? or in the elements, hook?
Try one of these methods:
https://docs.generatepress.com/article/adding-php/
Thanks, it's worked!
add_action( 'pre_get_posts', function( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( is_category() ) {
$query->set( 'posts_per_page', 9 );
}
} );
Glad to hear :)
Thanks ;)
No problem :)
Hello, which PHP needs to be described here? The Archive.php in the theme?