Custom sidebar category listing?

I am trying to make a custom Category Display on my side bar and for that I need some way to get both, the category list and the child list in 2 different arrays or something alike…

First, I tried the function get_categories, but it does not allow me to gather top-level categories only:

Read More
$args=array('orderby' => 'name', 'order' => 'ASC');
$categories=get_categories($args);

Then, I moved to wp_list_categories which does what I want. However, the return does not give me an array of data that I can query. It gives me a simple HTML-formatted list ready to print out:

$categories=wp_list_categories('echo=0&style=none&orderby=name&order=ASC&depth=1&title_li=');
  • Is there a way to gather the top
    level categories list in a way I can
    personalize it as I wish ?

    For Example:

    foreach($category_list as $category) {
        echo ' <li>';
        echo '  <a title="' . sprintf( __( "View all posts in %s" ), $category->cat_name ) . '" href="' . get_category_link($category->cat_ID) . '">' . $category->cat_name . ' (' . $category->cat_ID .') </a>';
        echo '  <a onclick="s_toggleDisplay(document.getElementById('CHILD CATS'), this, '▼', '▲');" href="javascript:void(null);">▼</a>';
        echo ' </li>';
    }
    

Why do I want the top-level only ? Because, I wanted to make a show/hide function for the children of the top-level category. If you have another way to accomplish this or suggestion, let me know.

Related posts

Leave a Reply

1 comment

  1. You can skip categories that have parent in your loop:

    foreach($category_list as $category) {
    
    if( '0' != $category->parent )
        continue;
    

    I’ve looked through the source, but it seems depth is only taken in account in wp_list_categories() and you will probably need to extend Walker_Category class to custom walker there to make changes to output.

    Actually, this might be a good idea if you need a really complex categories output format.