Using two nested foreach
you prevent n+1 db queries, where n is the number of child terms:
<?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="https://wordpress.stackexchange.com/questions/108522/<?php echo $album_url; ?>" rel="nofollow">
<img src="<?php echo $cover; ?>" alt="<?php echo $term->name; ?>">
</a>
<div class="caption">
<a href="https://wordpress.stackexchange.com/questions/108522/<?php echo $album_url; ?>">
<?php echo $children['parent_name'] . ' - ' . $term->name; ?>
</a>
</div>
</div>
</li>
<?php } } } } ?>
… and please, the right PHP open tag is <?php
not <?
.