根据帖子数量和类别列出自定义分类

时间:2011-06-21 作者:user1327

我有一个称为“自行车类别”的自定义分类法、一个称为“品牌”的自定义术语和一个称为“自行车”的自定义帖子类型

我想列出每个自行车类别,然后在下面列出所有有自行车的品牌。

我已经完成了一半,但似乎资源非常紧张/冗长,我肯定我走错了方向。有人能提出更好的方法吗?

<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 个回复
SO网友:Stephen Harris

我会使用get_queried_object() (see this post) 而不是$wp_query->query_vars

您还应该使用$term->slug (和$category->slug) 而不是$term->name.

除此之外,你的方法和其他方法一样好。

结束

相关推荐