子类别显示在父类别之前

时间:2012-03-24 作者:user1178152

我目前正在使用以下代码来回应我帖子的类别:

<?php foreach((get_the_category()) as $category) { echo $category->cat_name . \' \'; } ?> 
例如,我有一篇帖子,上面有一个父类兴趣爱好和一个子类音乐。使用此代码时,它显示为

MUSIC HOBBIES
虽然我想将其显示为,

HOBBIES MUSIC
我怎样才能做到这一点?顺便说一句,爱好的cat id是7,爵士乐的cat id是8。

1 个回复
SO网友:Boone Gorges

这是一个棘手而有趣的问题。为类别的白名单编写硬编码的顺序非常容易,但真正的排序算法需要递归,它将处理任意数量的类别和任意树深度。下面的内容可能不是最有效的解决方案,但无论长度或深度如何,都可以对类别列表进行排序:

$categories = get_the_category();

// Assemble a tree of category relationships
// Also re-key the category array for easier
// reference
$category_tree = array();
$keyed_categories = array();

foreach( (array)$categories as $c ) {
    $category_tree[$c->cat_ID] = $c->category_parent;
    $keyed_categories[$c->cat_ID] = $c;
}

// Now loop through and create a tiered list of
// categories
$tiered_categories = array();
$tier = 0;

// This is the recursive bit
while ( !empty( $category_tree ) ) {
    $cats_to_unset = array();
    foreach( (array)$category_tree as $cat_id => $cat_parent ) {
        if ( !in_array( $cat_parent, array_keys( $category_tree ) ) ) {
            $tiered_categories[$tier][] = $cat_id;
            $cats_to_unset[] = $cat_id;
        }
    }

    foreach( $cats_to_unset as $ctu ) {
        unset( $category_tree[$ctu] );
    }
    $tier++;
}

// Walk through the tiers to order the cat objects properly
$ordered_categories = array();
foreach( (array)$tiered_categories as $tier ) {
    foreach( (array)$tier as $tcat ) {
        $ordered_categories[] = $keyed_categories[$tcat];
    }
}

// Now you can loop over them and do whatever you want
foreach( (array)$ordered_categories as $oc ) {
    echo $oc->cat_name . \' \';
}
注意,如果get_the_category() 返回具有相同父级的多个类别,此算法将它们视为相同的(也就是说,它们按相同的顺序放置get_the_category() 返回它们)。

结束