Skip to content

Instantly share code, notes, and snippets.

@vajrasar
Created March 7, 2014 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vajrasar/9410466 to your computer and use it in GitHub Desktop.
Save vajrasar/9410466 to your computer and use it in GitHub Desktop.
To achieve a pattern where Parent Category shows without count and their respective Child categories shown with count.
<?php
/*
This is what I wrote to achieve a pattern where Parent Category shows without count
and their respective Child categories shown with count. I am pretty sure that there is some neat
way to get this done, but I was not able to find that. Pls mention in comments if you knw any
other alternative approach.
Ex:
Parent
-Child1 (10)
-Child2 (99)
*/
$noparent = array();
$childs = array();
$taxonomy = "category";
$i=0;
$args = array(
'hide_empty' => 0,
);
$cats = get_categories($args);
// Gets all parent and single categories
foreach ((array)$cats as $cat) {
$catparent = $cat->category_parent;
if($catparent == 0) {
$noparent[$i]['name'] = $cat->name;
$noparent[$i]['id'] = $cat->term_id;
$i++;
}
}
echo "<div class='cat-content'>";
// Make display of parent category (without count) and their children categories (with count)
foreach ((array)$noparent as $nop) {
$childs = get_term_children( $nop['id'], $taxonomy );
if( !empty( $childs ) ) {
echo "<span class='catlist'>";
echo "<b>" . $nop['name'] . "</b>";
foreach ((array)$childs as $child) {
$argss = array(
'style' => 'list',
'show_count' => 1,
'hide_empty' => 0,
'child_of' => $nop['id'],
'title_li' => '',
'taxonomy' => 'category',
);
wp_list_categories( $argss );
//echo "<br />";
break;
}
echo "</span>";
} else {
echo "<br />";
echo "<span class='catlist'>";
echo "<b>" . $nop['name'] . "</b>";
echo "</span>";
echo "<br />";
}
}
echo "</div>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment