In WordPress
, I want the pagination to skip certain post categories.
I have two pages with blog posts. One page is the regular WordPress
blog page. It displays all blog posts except for one category. The second page displays only this one category of blog posts. So far, so good. I query
this via Elementor and it works just fine.
Now, when I click through the pagination on either of these two blog pages, it will just go through all blog posts.
The result I would like to achieve is that the pagination on the regular blog page skips all posts of that one excluded category ID 43
. On the second blog page (the one that displays only category ID 43
), the pagination should only navigate through posts in category ID 43
.
Is this possible via functions.php
?
I hide the special category from the blog page like so:
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-43' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );
EDIT:
I found these two functions for the next and previous links in the WordPress
documentation: (1 2)
// next
function next_post_link( $format = '%link »', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_next_post_link( $format, $link, $in_same_term, $excluded_terms, $taxonomy );
}
// previous
function previous_post_link( $format = '« %link', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_previous_post_link( $format, $link, $in_same_term, $excluded_terms, $taxonomy );
}
Could I hook into them via functions.php
and a if page ID is... query
and use a category name in $excluded_terms = ''
?
My Answer:
>is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-43' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );
To exclude the category from pagination, you can modify the above function to also exclude the category from pagination. Here's how you can achieve this:
function exclude_category_from_pagination( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-43' );
}
if ( $query->is_paged() ) {
$query->set( 'cat', '43' );
}
}
add_action( 'pre_get_posts', 'exclude_category_from_pagination' );
This function will exclude category ID 43 from the main blog page and include only category ID 43 for pagination on the second blog page. Make sure to replace '43' with the actual category ID you want to exclude/include.
Rate this post
5 of 5 based on 8271 votesComments