Filter CPT posts by one or more categories

I'm trying to filter the posts on a CPT by one or more categories.Here's what I have so far:$args = array(

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 badges
Add a comment  | 

1 Answer 1

Reset to default 0

Actually, 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

相关推荐

  • Filter CPT posts by one or more categories

    I'm trying to filter the posts on a CPT by one or more categories.Here's what I have so far:$args = array(

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信