Filtering posts based on three taxonomies

Question

I’ve built a filterable post listing where the user can filter based on two taxonomies, this is working but I now want to add a third taxonomy to the filter, but I think the logic I’m using isn’t very efficient.

Here’s my code for the two taxonomy filter. If I was to add a third taxonomy using this approach I would need to add an If/Else block for each combination, but there must be a better way of doing this?

function filter_ajax() {
$category = $_POST['category'];
$sector = $_POST['sector'];
$size = $_POST['size'];
$args = array(  
    'post_type' => 'project',
    'post_status' => 'publish',
    'posts_per_page' => -1
);

if(isset($category) && isset($sector)) {
    $args["tax_query"] = array(
        'relation' => 'AND',
        array(
        'taxonomy' => 'project_category',
        'terms' => array($category)
        ),
        array(
            'taxonomy' => 'sector',
            'terms' => array($sector)
        )
    );
} else if(isset($sector)) {
    $args["tax_query"] = array(
        array(
            'taxonomy' => 'sector',
            'terms' => array($sector)
            )
    );
} else if (isset($category)) {
    $args["tax_query"] = array(
        array(
            'taxonomy' => 'project_category',
            'terms' => array($category)
            )
    );
}

I’m passing in the term id for the taxonomies: category, sector and size. Sometimes these will be unset if the user hasn’t selected a term in a particular taxonomy.

Is there a better way of structuring this request without having to add more if/else statements?

0
FreddieE 2 months 0 Answers 9 views 0

Leave an answer