0

I'm using this code below to print all my children categories with their parent name, but it only works with ASC order, if I change to DESC order, it shows an empty result. Is there anything I can do to revert this?

<?
$_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) {
?>
--- <?php echo $children['parent_name'] . ' - ' . $term->name; ?>
<?
            }
        }
    }
}
?> 

You can see the working version at http://lyricssoup.com/. Any help is much appreciated!

  • Change 'id' in the query to 'ID' as the query does require the capitalisation The reason the desc works is because it's the default order in the query. – Gareth Gillman Jan 19 '14 at 18:36
  • 1
    Can you reformat your code so it's indented correctly? It makes it quite hard to read, and obscures potential errors. Any good editor should be able to auto-indent for you saving you the hassle – Tom J Nowell Jan 19 '14 at 20:01
  • Indentation fixed. Sorry! – Bruno Monteiro Jan 21 '14 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.