我正在使用custom taxonomies 和custom post type 在我的博客里,到目前为止一切都很顺利。
问题是,我做了一个小查询来列出我的所有子类别,但由于第10行的情况,现在我无法获得每个父类别的名称。
这是我的代码:
<?php
$args = array(
\'orderby\' => \'id\',
\'order\' => \'ASC\',
\'taxonomy\' => \'album\'
);
$categories=get_categories($args);
foreach($categories as $category) {
if($category->parent!=0) {
?>
<li class="span3">
<div class="thumbnail">
<a href="<? bloginfo(\'url\'); ?>/album/<?php echo $category->category_nicename; ?>" rel="nofollow">
<img src="<?php bloginfo(\'url\'); ?>/covers/<?php echo $category->category_nicename; ?>.jpg" alt="">
</a>
<div class="caption">
<a href="<? bloginfo(\'url\'); ?>/album/<? echo $category->category_nicename; ?>">
<? echo $category->parent . \' - \' . $category->name; ?>
</a>
</div>
</div>
</li>
<?
}
}
?>
有解决方法吗?
最合适的回答,由SO网友:gmazzap 整理而成
使用两个嵌套foreach
禁止n+1 db查询,其中n是子项的数目:
<?php
$_cats = array();
$args = array(
\'orderby\' => \'id\', \'order\' => \'ASC\', \'taxonomy\' => \'album\'
);
$categories = get_categories($args);
if ( ! empty($categories) ) { foreach( $categories as $category ) {
if ( $category->parent != 0 ) {
if ( ! isset($_cats[$category->parent]) ) {
$_cats[$category->parent] = array( \'terms\' => array() );
}
$_cats[$category->parent][\'terms\'][] = $category;
} else {
if ( ! isset($_cats[$category->term_id]) ) $_cats[$category->term_id] = array();
$_cats[$category->term_id][\'parent_name\'] = $category->name;
$_cats[$category->term_id][\'terms\'] = array();
}
} }
if ( ! empty($_cats) ) { foreach( $_cats as $parentid => $children ) {
if ( ! empty($children[\'terms\']) ) { foreach( $children[\'terms\'] as $term ) {
$album_url = site_url() . \'/album/\' . $term->category_nicename;
$cover = site_url() . \'/covers/\' . $term->category_nicename . \'.jpg\';
?>
<li class="span3">
<div class="thumbnail">
<a href="<?php echo $album_url; ?>" rel="nofollow">
<img src="<?php echo $cover; ?>" alt="<?php echo $term->name; ?>">
</a>
<div class="caption">
<a href="<?php echo $album_url; ?>">
<?php echo $children[\'parent_name\'] . \' - \' . $term->name; ?>
</a>
</div>
</div>
</li>
<?php } } } } ?>
。。。请注意,正确的PHP open标记是
<?php
不
<?
.