Different number posts per page based on custom post type term id
-
20-05-2021 - |
Question
Trying to cobble together a function from various suggestions that sets the number of posts per page based on the custom post type category in question. For instance, an "Alphabetical" category contains 3500+ posts, so I want pagination, but a child category "A" contains 100 posts and I want to show them all without pagination. The term_id for "A" is 1858, for "Alphabetical" is 1853. Can I check for specific term ids in a conditional? Not like this of course, which was just guessing...
add_filter('pre_get_posts', 'limit_change_posts_archive');
function limit_change_posts_archive($query){
if ( is_archive && is_tax( 'pdsh_categories' ) && is_term( 1858 ) {
$query->set('posts_per_page', -1);
}
return $query;
La solution
You can achieve it with pre_get_posts
. With your current code there are multiple syntax errors. You have write it this way
add_filter('pre_get_posts', 'limit_change_posts_archive');
function limit_change_posts_archive($query){
if ( !is_admin() && $query->is_main_query() && is_archive() && is_tax( 'pdsh_categories' ) && is_term( 1858 )) {
$query->set('posts_per_page', -1);
}
return $query;
}
As is_term
is deprecated a different approach can be like this:
add_filter('pre_get_posts', 'limit_change_posts_archive');
function limit_change_posts_archive($query){
if ( !is_admin() && $query->is_main_query() && is_archive() && is_tax( 'pdsh_categories', 1858 )) {
$query->set('posts_per_page', -1);
}
return $query;
}
Again this above code needs to be tested.