Home > Software design >  This code is not filtering the category in wordpress. if i remove cat slug it's showing data bu
This code is not filtering the category in wordpress. if i remove cat slug it's showing data bu

Time:12-09

This code is not filtering the category in wordpress. if i remove cat slug it's showing data but i request for some specfic category it's not working please help me out of this

        $args = array(
            'post_type' => 'post',
            'posts_per_page' => intval( $items ),
            'paged'     => $paged
        );

        if ( ! empty( $cat_slug ) ) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'post_category',
                    'field'    => 'slug',
                    'terms'    => $cat_slug
                ),
            );
        }

        if ( ! empty( $exclude_cat_slug ) ) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'post_category',
                    'field' => 'slug',
                    'terms' => $exclude_cat_slug,
                    'operator' => 'NOT IN'
                ),
            );
        }       

CodePudding user response:

You are overriding tax_query. I revised your code. try the below code.

$tax_query = array( 'relation' => 'AND' );

if ( ! empty( $cat_slug ) ) {
    $tax_query[] = array(
        'taxonomy' => 'post_category',
        'field'    => 'slug',
        'terms'    => $cat_slug
    );
}

if ( ! empty( $exclude_cat_slug ) ) {
    $tax_query[] = array(
        'taxonomy' => 'post_category',
        'field'    => 'slug',
        'terms'    => $exclude_cat_slug,
        'operator' => 'NOT IN'
    );
}     

$args = array(
    'post_type'      => 'post',
    'posts_per_page' => intval( $items ),
    'paged'          => $paged,
    'tax_query'      => $tax_query
);

CodePudding user response:

taxonomy' => 'category', 'field' => 'slug', 'terms' => $cat_slug

Just remove Post_category to category

Now it will work. DTP addon NUSAFE THEME

  • Related