Resort get_categories

时间:2013-04-20 作者:CBeTJlu4ok

我有一个get\\u categories数组

$args=array(
    \'orderby\' => \'id\',
    \'order\' => \'ASC\',
    \'taxonomy\' => \'wpsc-variation\',
    \'hierarchical\' => 1,
    \'hide_empty\' => 0
);
$variationCategories=get_categories($args);
我将这些类别显示为复选框。

foreach($variationCategories as $category) {

    if (in_array($category->term_id, $parentArray)) {
        if ($category->parent == 0) {
            echo "</li><li class=\'formVariationParent\'><input type=\'checkbox\' checked name=\'variationParent[]\' autocomplete=\'off\' value=\'". $category->term_id ."\'>" . $category->name . "";
        } else {
            echo "<ul><li class=\'formVariationChild\'><input type=\'checkbox\' checked name=\'". $category->parent ."-". $category->term_id ."\' autocomplete=\'off\' value=\'1\'>" . $category->name . "</li></ul>";
        }
    } else {
        if ($category->parent == 0) {
            echo "</li><li class=\'formVariationParent\'><input type=\'checkbox\' name=\'variationParent[]\' autocomplete=\'off\' value=\'". $category->term_id ."\'>" . $category->name . "";
        } else {
            echo "<ul><li class=\'formVariationChild\'><input type=\'checkbox\' name=\'". $category->parent ."-". $category->term_id ."\' autocomplete=\'off\' value=\'1\'>" . $category->name . "</li></ul>";
        }
    }

}
问题是排序,我想按的父值排序$variationCategories[]This is a dumped version of $VariationCategories

按家长与usort订购没有问题:

function cmp($a, $b) {
    return strcmp($a->parent, $b->parent);
}
usort($variationCategories, "cmp");
但这只适用于子类别。但也有父值为“0”的父级。我想要的顺序是:0(父:0)1(父:3)2(父:3)3(父:3)4(父:0)5(父:4)6(父:4)7(父:4)

像这样screenshot

其中,颜色、大小和CPU数组有->(父级:0),其他数组按ID排序,但当我添加新类别时,它会在最后追加,因为它现在按ID排序

我可以借用/重新创建这样的阵列吗?

1 个回复
最合适的回答,由SO网友:fuxia 整理而成

WordPress中已经有这样一个功能:wp_terms_checklist(). 它在元数据库中用于post editor中的层次分类。也许你可以重复使用它?

以下内容未经测试,请仅作为指南,而不是完整的解决方案:

// File where "wp_terms_checklist()" is declared
require_once ABSPATH . \'wp-admin/includes/template.php\';

// Output will be printed immediately
wp_terms_checklist(
    0, // post ID
    array (
        \'descendants_and_self\' => 0,
        \'selected_cats\'        => FALSE,
        \'popular_cats\'         => FALSE,
        \'walker\'               => NULL,
        \'taxonomy\'             => \'wpsc-variation\',
        \'checked_ontop\'        => FALSE
    )
);

结束