skip to Main Content

Let’s say I have a website which sells cars.

I’m using a custom taxonomy called brand for the manufacturer (like BMW, Audi, …) and a custom taxonomy called type for the type of cars (like SUV, Coupe, …).

For the cars itself I’m using a custom post type called models.

Now I want to show every car brand in the taxonomy archive for type (All brands with SUVs).

To do that, I’m trying to get all brands and filter them with all types.
As result there should be a list with all car brands that have SUVs.

Here’s my current code to get a list of brands:

$taxonomies = get_terms( array(
    'taxonomy' => 'brand',
    'hide_empty' => false
) );
 
if ( !empty($taxonomies) ) :
    $output = '<select>';
    foreach( $taxonomies as $category ) {
        if( $category->parent == 0 ) {
            $output.= '<optgroup label="'. esc_attr( $category->name ) .'"></optgroup>';
        }
    }
    $output.='</select>';
    echo $output;
endif;

I couldn’t find a way to add a second taxonomy to this snippet.
Is this the wrong approach?

Maybe I need to get the custom post types (models) first to check which one has both terms?

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution that works:

    $productcat_id      = get_queried_object_id();
    $args = array(
        'numberposts' => -1,
        'post_type' => array('models'),
        'tax_query' => array(
            array(
                'taxonomy' => 'brand',
                'field'    => 'term_id',
                'terms'    => $productcat_id,
            ),
        ),
    );
    
    $cat_posts  = get_posts($args);
    
    $my_post_ids = wp_list_pluck ($cat_posts, 'ID');
    $my_terms    = wp_get_object_terms ($my_post_ids, 'types');
    
    if ( !empty($my_terms)) :
        echo '<ul>';
            foreach( $my_terms as $my_term ):
    
                $brand_name = $my_term->name;
                $brand_link = get_term_link($my_term);
    
                echo '<li><a alt="'.$brand_name.'" href="'.esc_url( $brand_link ).'">'.$brand_name.'</a></li>';
    
            endforeach;
        echo '</ul>';
    endif;
    

  2. This article has a really helpful breakdown.

    I needed to get the taxonomies that were part of another taxonomy for use in creating a dropdown (and some other uses.) This code allowed me to identify the "categories" that were part of a particular "destination".

    $dest_slug = get_query_var('term');
    $desination_ids = get_posts(array(
    'post_type' => 'item',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'destinations',
            'field' => 'slug',
            'terms' => $dest_slug
        )
    ),
    'fields' => 'ids'
    ));
    $categories = wp_get_object_terms($desination_ids, 'category');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search