how to create texT query in wordpress

i want to create a text query. If category have same parent than add relation OR Other wise AND. Please see below screenshot so you can get more idea about that. I used pre_get_posts action for bind this query based on user select and display search result. Below code is add with AND relationship for all category.

function advanced_search_query($query) {

if($query->is_search()) {
$taxes = $_REQUEST['cat_project_category'];
    $tax_query = array( 
                        'relation' => 'AND' );
        for($i=0;$i < count($_REQUEST['cat_project_category']);$i++)
        {
            $tax_query[] = array(
                            'taxonomy' => 'project_category',
                            'terms' => array($_REQUEST['cat_project_category'][$i]),
                            'field' => 'term_id'
                         );
        }
    $query->set( 'tax_query',$tax_query);
    //echo '<pre>';
    //print_r($query);
    return $query;
}
}
add_action('pre_get_posts', 'advanced_search_query', 1000);

Related posts

1 comment

  1. You could query each category, get the parent ID, put them in an array and look at the end if this array have only one value inside.

    $taxes = $_REQUEST['cat_project_category'];
    $tax_query = array();
    $parents_categories = array();
    for($i=0;$i < count($_REQUEST['cat_project_category']);$i++) {
        $tax_query[] = array(
            'taxonomy' => 'project_category',
            'terms' => array($_REQUEST['cat_project_category'][$i]),
            'field' => 'term_id'
        );
        $category = get_category($_REQUEST['cat_project_category'][$i]),
        if($category != 0)
        $parents_categories[$category] = true;
    }
    if(count($parents_categories) == 1) {
        $tax_query['relation'] = 'OR';
    } else{
        $tax_query['relation'] = 'AND';
    }
    $query->set( 'tax_query',$tax_query);
    

Comments are closed.