Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

i have a custom taxonomy called 'bike-category' and a custom term called 'brand' and a custom post type called 'bikes'

I want to list each bike-category then underneath list all brands only which have bikes in them.

Ive half got there however it seems very resource heavy/long winded and im sure im going about this the wrong way. Could someone suggest a better approach?

<ul>
<?php
// set up taxonomies
$tax_one = 'bike-category';
$tax_two = 'brands';
$post_type = 'bikes';

$categories = get_categories( array(
    'type'                     => $post_type,
    'orderby'                  => 'name',
    'order'                    => 'ASC',
    'hide_empty'               => 0,
    'hierarchical'             => 1,
    'taxonomy'                 => $tax_one ));

    foreach ( $categories as $category ) : // list all categories

    if($category->slug == $wp_query->query_vars['bike-category']) { $selected = ' class="selected"'; } else { $selected = ''; }

        echo '<li'.$selected.'><a href="'.get_bloginfo('url').'/bikes/'.$category->slug.'">'.$category->name.'</a><ul>';

            $terms = get_terms( $tax_two, array( 'hide_empty' => 0 ) );

            foreach ( $terms as $term ) :  // list all brands in each category

                $myquery['tax_query'] = array(
                    array(
                        'taxonomy' => $tax_one,
                        'terms' => array($category->name),
                        'field' => 'slug'
                    ),
                    array(
                        'taxonomy' => $tax_two,
                        'terms' => array($term->name),
                        'field' => 'slug'
                    )
                );
                $the_posts = new WP_Query($myquery);
        print_r($myquery);
                if ( $the_posts->have_posts() ) : // if there are posts in the current brand and category then display it

                    echo '<li><a href="'.get_bloginfo('url').'/bikes/'.$category->slug.'/'.$term->slug.'">'.$term->name.'</a></li>';

                endif;

            endforeach;

        echo '</ul></li>';

    endforeach; ?></ul>
share|improve this question

1 Answer 1

I would use get_queried_object() (see this post) rather than $wp_query->query_vars

Also you should use $term->slug (and $category->slug) instead of $term->name.

Apart from that, your method is as good as any.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.