0
votes

I am filtering custom post types using ajax. I am able to filter using single taxonomy but how to filter results with multiple taxonomies.

This is the query i tried:

Code:

$args=array('orderby'=>'date','post_status'=>'publish');

//sort by bank if isset
if(isset($_POST['bank']))
{
    $args['tax_query']=array(
        array(
                'taxonomy'=>'banks',
                'field'=>'id',
                'terms'=>$_POST['bank']
        )
    );
}
if(isset($_POST['card_type']))
{
    $args['tax_query']=array(
        'relation'=>'AND',
        array(
                'taxonomy'=>'cardtype',
                'field'=>'id',
                'terms'=>$_POST['card_type']
        )
    );
}
$query=new WP_Query($args);

But it only shows result with filtering from one taxonomy not both.

1

1 Answers

0
votes

I think you are working on right track but a small mistake in argument may cause result to be rendered wrong. Instead of 'relation'=>'AND', use 'relation'=>'OR'

'relation'=>'AND' will fetch result when both taxonomy condition match, while 'relation'=>'OR' condition will compare with any of the taxonomy.

click here to view the WP Query arguments

Actually yout array formation is wrong for tax_query. Please check updated code below. If you don't use $args['tax_query']['relation']= 'AND', then also it will work for you.

Please have a try with below code snippet.Update you code with below snippet.

$args = array(
            'orderby'=>'date',
            'post_status'=>'publish'
        );

//sort by bank if isset
if(isset($_POST['bank'])){
    $args['tax_query'][]= array(
                'taxonomy'=>'banks',
                'field'=>'id',
                'terms'=>$_POST['bank']
                );
}
if(isset($_POST['card_type'])){
    $args['tax_query']['relation']=   'AND';//you can remove this

    $args['tax_query'][]=   array(
                            'taxonomy'=>'cardtype',
                            'field'=>'id',
                            'terms'=>$_POST['card_type']
                    );

}
$the_query = new WP_Query( $args );