why can’t you use wp_list_categories? What is it about the theme that doesn’t allow you?
If you can get this generated code with wp_list_categories, then I would like to see how it is done.
<li id="cat18" class="current" ><a>Category Title</a></li>
Here is the original code:
<?php $cats = get_categories('hide_empty=0&child_of=16&depth=2');
foreach ((array)$cats as $categ) {
echo '<li id="cat'.$categ->cat_ID.'" ';
if (($category[0]->cat_ID==$categ->cat_ID)&&($tagged=='')){ echo 'class="current" ';}
echo '><a>'. $categ->cat_name . '</a></li>';
}?>
I’m having this same problem. Wp_list_categories doesn’t give me the flexibility I need, because I can’t seem to display both title and description with that function. But I need to be able to limit depth with get_categories.
Does anyone have ideas on how I might be able to write a wrapper function around get_categories that would allow me to display subcategories to only one depth?
Thanks in advance for your help.
i also request this, need depth on get_categories
need more vanilla functions that don’t try to create the links and format the output. just return the values
I agree, joshua4. This is how I ended up solving my problem. It’s inelegant, but it works.
If you, like me, want to limit get_categories to a depth of one, you can do this:
<?php global $ancestor; // Declare global ancestor variable ?>
<?php foreach ($categories as $cat) {
if ($cat->cat_ID != 1) { // If category is not uncategorized ...
if (cat_is_ancestor_of($ancestor, intval($cat->cat_ID)) == false) { // .. and if the previous category in the loop wasn't the ancestor of this one ... ?>
<h2><a href="<?php echo get_category_link($cat->cat_ID); ?>"><?php echo ($cat->cat_name); ?></a></h2>
<?php echo ( category_description($cat->cat_ID) ); ?>
<?php
$ancestor = intval($cat->cat_ID); }; // make this category the new ancestor
};
};
?>
If you want to limit depth to two (like displayname does above), you could declare a global $grandparent variable, then at the end of the loop, make the former $ancestor the new $grandparent and the current category the new $ancestor. Then just add another $greatgrandparent if you want a depth of three levels, and so on and so on.
This is a mighty hacky way of just getting depth for get_categories. I think I’ll submit a ticket for that.
Thanks for the hack, mthomps.
I also put in my vote for adding “depth” but this will get me through for the moment!
Hi,
I was just looking for a way to display the number of the top categorys (depth=1).
Maybe this is not exectly what you are looking for, but i think you might customise it for your needs.
I used a db query to get my results:
$numcats = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE parent=0
AND taxonomy = 'category';");
echo $numcats;
It displays exectly what I needed (the number of the topcategories) but if you use an other query string you might get your results.