I want to get all categories in wordpress site but separately parent and child categories(in such way it’s easily for me to style). In the following code I get parent categories but all children categories are repeated for every parent.
Thanks!
<?php
$args = array(
'orderby' => 'name',
'parent' => 0
);
$categories = get_categories( $args );
$categories_sub = get_categories();
foreach ( $categories as $category ) {
echo '<ul class=" span-5 colborder list_main "> <a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a><br/>';
foreach ( $cat->parent > 1 and $categories_sub as $cat) {
$temp=$category->name + '/';
if(get_category_parents($cat)==$temp) {
echo '<a href="' . get_category_link( $cat->term_id ) . '">' . $cat->name . '</a><br/>';
}
$temp="";
}
echo '</ul>';
}
?>
There are several ways to create HTML list of categories.
wp_list_categories()
Default CSS selectors
Simplest way is to display a list of categories with wp_list_categories() and style the output with default CSS selectors:
The Walker_Category class
The
Walker
class is for traversing the hierarchical data like menus or categories. It is an abstract class that has four abstract methodsstart_el()
,end_el()
,start_lvl()
,end_lvl()
. It is not required to override all abstract methods of the class, only those methods that are needed.Recursive Function
Recursive Function is also a good way to traverse through categories. This way you have to manually get the categories on each node. Since the get_categories() function returns all the children categories in all subnodes, id of the current category must be passed on to be able to display only the current level categories.
i had implemented this code a while ago but you can give it a try..