tags:

views:

91

answers:

3

Hi I'm looking to obtain all the (parent) categories with their children accordingly (assuming you don't have grandchildren) and make the following structure

  <div class="box">
    <h3><a href="#">Parent Category I</a></h3>
    <ul>
      <li><a href="#">sub cat 1</a></li>
      <li><a href="#">sub cat 2</a></li>
      <li><a href="#">sub cat 3</a></li>
    </ul>
  </div>
  <div class="box">
    <h3><a href="#">Parent Category II</a></h3>
    <ul>
      <li><a href="#">sub cat 1</a></li>
      <li><a href="#">sub cat 2<</a></li>
      <li><a href="#">sub cat 3</a></li>
    </ul>
  </div>

I figured it's something like (don't mind the syntax) however I don't know how to obtain those (parent)categories and their children:

$parents = ... ;

foreach($parents as $parent){
<div>
<h3>$parent</h3>

$children = ...;
<ul>
foreach ($children as $child){
<li>$child</li>
}
</ul>

</div>

}
A: 

I'd start with get_categories() and wp_list_categories() (the function, while it may not be perfect for your needs, is very flexible), and guess that you'd have to use a for-loop to go through the parent categories with a nested loop to handle the children (as your pseudo-code suggests). Especially with wp_list_categories(), you probably won't be able to get the exact structure you want, but at least something that you'll be able to style reasonably.

Benny Jobigan
A: 

as what benny posted, wp_list_categories would be your best function to use.

Perhaps you should rethink the html structure as the way wordpress formats your category list is in an unordered list, this is so that if your styling fails to load it is presented in a natural format. However you can alter this behaviour by changing the value of 'hierarchical' to false.

Hope this helps :)

Rob
A: 

ok I figured it out myself thanks anyway Benny & Rob

I basicly made 2 functions

function getParentCategories() {
    global $wpdb;
    $sql = "SELECT term_id as id, name, slug FROM wp_terms where term_id in (SELECT term_id FROM wp_term_taxonomy where parent = 0 and taxonomy = 'category') order by name asc";
    $parents = $wpdb->get_results( $sql );
    return $parents;
}

function getChildCategories($id) {
        global $wpdb;
        $sql = "SELECT term_id as id, name, slug FROM wp_terms where term_id in (SELECT term_id FROM wp_term_taxonomy where parent = $id and taxonomy = 'category')  order by name asc";
        $children = $wpdb->get_results( $sql );
        return $children;
    }
Ayrton