I'm trying to filter the posts on a CPT by one or more categories.
Here's what I have so far:
$args = array(
'post_type' => 'cpt-name',
'posts_per_page' => -1,
);
// cat_term_id have been registered as a custom query var
$categories = get_query_var( "cat_term_id" );
if ( !empty( $categories ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $categories,
'include_children' => false,
),
);
}
$filtered_posts = get_posts( args );
The query works, the problem is that is bringing all the posts on the CPT, and what I want is to only get the posts using the categories passed by cat_term_id
.
Am I missing something?
I'm trying to filter the posts on a CPT by one or more categories.
Here's what I have so far:
$args = array(
'post_type' => 'cpt-name',
'posts_per_page' => -1,
);
// cat_term_id have been registered as a custom query var
$categories = get_query_var( "cat_term_id" );
if ( !empty( $categories ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $categories,
'include_children' => false,
),
);
}
$filtered_posts = get_posts( args );
The query works, the problem is that is bringing all the posts on the CPT, and what I want is to only get the posts using the categories passed by cat_term_id
.
Am I missing something?
Share Improve this question asked Dec 7, 2019 at 23:45 darkflamemasterdarkflamemaster 212 bronze badges1 Answer
Reset to default 0Actually, the query was working as expected.
The problem was that with the pagination call:
the_posts_pagination(array(
'screen_reader_text' => 'Navigation',
'prev_text' => '<i class="fa fa-angle-left" ></i>',
'next_text' => '<i class="fa fa-angle-right" ></i>',
));
From reading the code and finding this question on StackOverflow, I discovered that the function the_posts_pagination
is a wrapper for the function get_the_posts_navigation
which uses $GLOBALS['wp_query']->max_num_pages
to know the number of pages to paginate. And because I'm using a custom query, my pagination was out of context.
I hope this helps someone.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744928390a4601582.html
评论列表(0条)