Search code examples
phpwordpresstaxonomy

Wordpress Get Terms For Taxonomy Wordpress


I have two taxonomies and I need to build a list of terms of one taxonomy based on the other.

Taxonomy 1 - Auto_Brand

Taxonomy 2 - City

I know I can use $terms = get_terms("auto_brands"); or $terms = get_terms("city");, but how can I structure code to grab the city only where that city has an auto_brand attached to it?


Solution

  • Taxonomies don't interact directly with other Taxonomies. They only interact with - and encapsulate - Post Objects. The only way I can think of doing this is by running a Taxonomy Query using WP_Query to gather all posts that utilize BOTH taxonomies, and then loop through each post to build an array of unique terms:

    $args = array(
        'post_type' => 'post',
        'tax_query' => array(
            'relation' => 'AND',
            array('taxonomy' => 'auto_brand'),
            array('taxonomy' => 'city')
        )
    );
    $q = new WP_Query($args); //Get the posts
    
    $found_terms = array(); //Initialize Empty Array
    $taxonomies = array('auto_brand', 'city'); //Taxonomies we're checking
    $args = array('fields'=>'names'); //Get only the names
    foreach($q->posts as $t_post) //Begin looping through all found posts
    {
        $post_terms = wp_get_post_terms($t_post->ID, $taxonomies, $args);
        $found_terms = array_merge($found_terms, $post_terms); //Build Terms array
    }
    $unique_terms = array_unique($found_terms); //Filter duplicates
    

    This is untested, but it should get you started in the right direction.