Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am trying to display a list of all categories and sub-categories underneath that category, I have managed to get a list of all categories that are parents but am struggling to detect if it has children and then display them in the current loop. Here is my code at the moment:

$args = array(
  'orderby' => 'name',
  'parent' => 0
  );
$categories = get_categories( $args );
foreach ( $categories as $category ) {

    echo '<a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a><br />';

}

I have found a few functions on here about detecting if the category has children, but am struggling to actually display the children (up to one level) under this link.

Any help is greatly appreciated, Simon

share|improve this question
add comment

1 Answer

Solved with the following:

$args = array(
  'orderby' => 'name',
  'parent' => 0
  );
$categories = get_categories( $args );
$first = true;
  foreach ($categories as $category) {
    if ( $first )
    {
        echo '<li class="title" style="border-top: 0px;"><a href="acatalog/abovegroundpools.html">'.$category->cat_name.'</a>';
        $first = false;
    }
    else
    {
        echo '<li class="title"><a href="acatalog/abovegroundpools.html">'.$category->cat_name.'</a>';
    }
    $theid = $category->term_id;
    $children = $wpdb->get_results( "SELECT term_id FROM $wpdb->term_taxonomy WHERE parent=$theid" );
        $no_children = count($children);
    if ($no_children > 0) {
        echo "<ul>";
        $args2 = array(
         'orderby' => 'name',
         'parent' => 2
         );
        $args2["parent"]=$category->term_id;
        $categories2 = get_categories( $args2 );
         foreach ($categories2 as $category2) {

            echo '<li><a href="acatalog/Inflatable-Hot-Tubs.html">'.$category2->cat_name.'</a></li>';

        }
        echo '</ul>';
    } else {
    echo '</li>';
    }

  }
 ?>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.