我正在使用WordPress 3.1.3,并试图制作一个“产品”菜单,其中每个类别都有帖子数量。像这样:
新车(4)宝马(2)福特(1)日产(1)二手车(10)宝马(3)福特(1)日产(6)为此,我创建了定制post类型Cars
和分类法Type
和Brand
. 不确定这是否是最好的方法,但下面是我的代码:
<?php $auto_types = get_terms(\'type\', \'hide_empty=1\'); ?>
<ul>
<?php foreach( $auto_types as $auto_type ) : ?>
<li>
<a href="<?php echo get_term_link( $auto_type->slug, \'type\' ); ?>">
<?php echo $auto_type->name; ?> (<?php echo $auto_type->count; ?>)
</a>
<?php
$terms = get_terms(\'brand\');
$count = count($terms);
if($count > 0) :
?>
<ul>
<?php foreach ($terms as $term) : ?>
<li>
<a href="/?type=<?php echo $auto_type->slug ?>&brand=<?php echo $term->slug ?>">
- - <?php echo $term->name; ?> (<?php echo $term->count; ?>)
</a>
</li>
<?php endforeach ?>
</ul>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
所以我的问题是:这是一个好方法吗Edit - 我已经设法解决了第二个问题,但我仍然不确定这是否是一个好方法。以下是新代码:
<?php $auto_types = get_terms(\'type\', \'hide_empty=1\'); ?>
<ul>
<?php foreach( $auto_types as $auto_type ) : ?>
<li>
<a href="<?php echo get_term_link( $auto_type->slug, \'type\' ); ?>">
<?php echo $auto_type->name; ?>
</a>
<?php $auto_brands = get_terms(\'brand\', \'parent=0\' ); ?>
<ul>
<?php foreach ($auto_brands as $auto_brand) : ?>
<?php $brand_filter[\'tax_query\'] = array(
\'relation\' => \'AND\',
array(
\'taxonomy\' => \'type\',
\'terms\' => array($auto_type->slug),
\'field\' => \'slug\',
),
array(
\'taxonomy\' => \'brand\',
\'terms\' => array($auto_brand->slug),
\'field\' => \'slug\',
),
);
$tax_query = new WP_Query($brand_filter);
$count = 0;
if ( $tax_query->have_posts() ) : while ( $tax_query->have_posts() ) : $tax_query->the_post();
$count++;
endwhile; endif; wp_reset_postdata();
if ( $count > 0 ) : ?>
<li>
<a href="/?type=<?php echo $auto_type->slug ?>&brand=<?php echo $auto_brand->slug ?>">
- - <?php echo $auto_brand->name; ?> (<?php echo $count; ?>)
</a>
</li>
<?php endif; endforeach ?>
</ul>
</li>
<?php endforeach ?>
</ul>
Edit 2 - 已更改query_posts()
方法到wp_query()
(多亏了VicePrez),但使用query只获取正确的帖子计数是有效的还是有更好的方法来创建此菜单?