am trying to get all the categories on my wordpress as a heirarchial multidimensional array of objects of type category.
There are 2 functions in wordpress that kind of do what I want, but not exactly :
1) get_categories() – This one does return an array of category objects, which is great, but then the array is a flat one, where there is no differentiation between which category is a parent or which one is a child.
2) wp_list_categories() – which can return the categories with the herarchy intact, but problem is that the return value is html, and I need the categories to still be objects.
For example, if I had the following 3 trees as my parent-less categories :
/*
tree_stump
tree1
branch1
tree2
branch2
twig2
leaves2
flowers2
fruits2
*/
I am trying to get a return value which could be something like:
$cat_tree=array( 1=>$tree_stump,2=>array(1=>$tree1,2=>$branch1),3=>array(1=>$tree2,2=>array(1=>$branch2,2=>array($twig2,$leaves2,$flowers2,$fruits2 ) ) ) );
where each member of the multi dim array is still an object, and in all the child arrays, the first one is the parent of the rest of the members. I guess this would need some kinda recursive stuff – the stuff that gives me jitters !
Not sure if I made sense, please do let me know if I need to be more clear..
Thanks for reading.
Here’s my version which assumes $categories is the output of get_categories() but it doesn’t matter what order they come in.
this is what i did:
First get an array using get_categories(). Then transform it into a new array.
I’m assuming that all children are below its parents in the original array.
Hope this is still useful for someone
get_categories() returns an array with lots of properties you can use to build the array. namely
$category->category_parent
and$category->parent