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 need more control over the category listing output, so I'm using get_categories (http://codex.wordpress.org/Function_Reference/get_categories), instead of wp_list_categories (http://codex.wordpress.org/Template_Tags/wp_list_categories).

This function returns a flat array of objects ordered by a certain attribute. How can I build a hierarchical list from it like wp_list_categories() does?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

The most ideal solution for walking over the data is to use the WordPress walker class.

http://codex.wordpress.org/Function_Reference/Walker_Class

You won't find many an example around the web for using it, but one was given by Scribu here.

http://scribu.net/wordpress/extending-the-category-walker.html

You can also look to the classes WordPress uses to extend the walker as further examples.

http://core.trac.wordpress.org/browser/tags/3.0.1/wp-includes/classes.php

Hope that helps..

share|improve this answer
    
thanks, I ended up creating my own walker.. –  Alex Nov 20 '10 at 18:21
    
You're welcome.. :) –  t31os Nov 20 '10 at 22:54

how to build a hierarchical tree from get_categories

see: http://stackoverflow.com/questions/3287603/wordpress-wp-list-categories-problem

in that answer Jan Fabry Jan Fabry jan-fabry jan-fabry does it like this:

$categories = get_categories();

// First index all categories by parent id, for easy lookup later
$cats_by_parent = array();
foreach ($categories as $cat)
{
  $parent_id = $cat->category_parent;
  if (!array_key_exists($parent_id, $cats_by_parent)) 
  {
    $cats_by_parent[$parent_id] = array();
  }
  $cats_by_parent[$parent_id][] = $cat;
}

// Then build a hierarchical tree
$cat_tree = array();
function add_cats_to_bag(&$child_bag, &$children)
{
   global $cats_by_parent;
   foreach ($children as $child_cat) 
   {
     $child_id = $child_cat->cat_ID;
     if (array_key_exists($child_id, $cats_by_parent)) 
     {
        $child_cat->children = array();
        add_cats_to_bag($child_cat->children, $cats_by_parent[$child_id]);
     }
     $child_bag[$child_id] = $child_cat;
   }
}
add_cats_to_bag($cat_tree, $cats_by_parent[0]);
share|improve this answer

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.