Resort get_categories

I have a get_categories array

$args=array(
    'orderby' => 'id',
    'order' => 'ASC',
    'taxonomy' => 'wpsc-variation',
    'hierarchical' => 1,
    'hide_empty' => 0
);
$variationCategories=get_categories($args);

I display those categories as a checkbox.

Read More
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>";
        }
    }

}

the problem is order, I want to order this by parent value of $variationCategories[]
This is a dumped version of $VariationCategories

it’s not problem order it by parent with usort:

function cmp($a, $b) {
    return strcmp($a->parent, $b->parent);
}
usort($variationCategories, "cmp");

but that’s only works for child categories.
but there are also parents which have parent value “0”.
The order I want is:

0 (parent:0)

1 (parent:3)

2 (parent:3)

3 (parent:3)

4 (parent:0)

5 (parent:4)

6 (parent:4)

7 (parent:4)

like this
screenshot

where color,size and CPU arrays has ->(parent:0)
and others are sorted by ID, but when I add new category it appends in the end, because it sorted by id by now

Can I resort/recreate such array?

Related posts

Leave a Reply

1 comment

  1. There is already a function in WordPress doing that: wp_terms_checklist(). It is used in the metabox for hierarchical taxonomies in the post editor. Maybe you can reuse that?

    The following is untested, see it just as a guide please, not as a complete solution:

    // 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
        )
    );