2

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>

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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