Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Anna Dadej
Anna Dadej
10,707 Points

Filter search result by either a taxonomy1, or a taxonymy2, or both taxonomy1 and taxonomy2 - how to modify this code?

Hi guys,

I have a problem which is driving me crazy and I hope someone will point me in a good direction.

I have a custom post type called Restaurants with two taxonomies Cities and Cuisine Type. I can select with checkboxes city/cities and cuisine type/types and it shows me all restaurants in selected options.

What doesn't work is selection only by a cuisine type or only by a city, so:

  1. If I check for example Chicago, italian food and french food - it shows all the restaurants with selected options

  2. But if I check only a city, or only a cuisine type - I get no results.

I think it's messed with "if" statement but I'm not a php master and can't figure out how to clean it... The code is:

<?php 

$search_city = true;
$cuisine = array_keys($_GET['cuisine-type']);

    if(isset($_GET['city'])){
        $city = array_keys($_GET['city']);
    }else{
        $city = array();
    }


    $loop = new WP_Query(array(
        'post_type' => 'restaurants',
        'tax_query' => array(
            'relation' => 'AND',
                array(
                'taxonomy' => 'city',
                'field'    => 'slug',
                'terms' => $city,
                ),  
                array(
                'taxonomy' => 'cuisine-type',
                'field' => 'slug',
                'terms' => $cuisine,
                ),
        ),
    ));

    get_template_part('archive', 'restaurants');

?>

If I remove 'relation' => 'AND' then I can search only by a city or by a cuisine type, when both city and cuisine-type are selected, the results will not show up.

1 Answer

I would make this child array dynamic

            'relation' => 'AND',
                array(
                'taxonomy' => 'city',
                'field'    => 'slug',
                'terms' => $city,
                ),  
                array(
                'taxonomy' => 'cuisine-type',
                'field' => 'slug',
                'terms' => $cuisine,
                ),

so you only apply the relationships the user has filtered by. It would be similar to your 'if (isset($_GET['city'])) {' statement.