J'ai besoin de plus de contrôle sur la sortie de la liste des catégories, donc j'utilise get_categories()
, au lieu de wp_list_categories()
.
Cette fonction retourne un tableau plat d'objets ordonnés par un certain attribut. Comment puis-je construire une liste hiérarchique comme le fait wp_list_categories()
?
La solution la plus idéale pour parcourir les données consiste à utiliser la classe WordPress Walker.
http://codex.wordpress.org/Function_Reference/Walker_Class
Vous ne trouverez pas beaucoup d’exemples sur le Web pour l’utiliser, mais Scribu en a donné un ici.
http://scribu.net/wordpress/extending-the-category-walker.html
Vous pouvez également vous référer aux classes utilisées par WordPress pour étendre le programme de navigation à titre d'exemples supplémentaires.
http://core.trac.wordpress.org/browser/tags/3.0.1/wp-includes/classes.php
J'espère que cela pourra aider..
get_categories
Voir cette question de débordement de pile . Dans la réponse Jan Fabry fait comme ceci:
$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]);