(WordPress)如何获取自定义分类父级名称?

时间:2013-07-31 作者:Bruno Monteiro

我正在使用custom taxonomiescustom 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>
    <?
    }
}
    ?>
有解决方法吗?

1 个回复
最合适的回答,由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<?.

结束

相关推荐

编辑“Kahi‘s Highlight Used Categories”插件代码--在帖子页面高亮显示父子类别

我试图突出显示(使用css)所选帖子中使用的子类别和父类别。因此,我找到了这个插件“Kahi’s Highlight Used Categories”。插件网站:http://kahi.cz/wordpress/highlight-used-categories-plugin/它的作用。。。它将“used cat”类和“used cat parent”类分别添加到子类别和主类别中进行样式化。问题是:我的网站(http://www.mpn.p.ht/wp_br2/), 有三大类:“男性”(意为男性)、“女性