Support » Fixing WordPress » Listing only top categories

  • How does one use to list only the top categories ? I don’t want any of the children:

    $categories= get_categories(‘child_of=0’);

    I can’t find a parameter that will tell get_categories to only list the root categories (those that have a parent of 0) and none of their children.

    Help ?

Viewing 6 replies - 1 through 6 (of 6 total)
  • You need to create a loop, where you cycle through ALL categories, check if they have parents, and not use those.

    Off the top of my head:

    foreach (get_the_category() as $cat) {
    	$parent = get_category($cat->category_parent);
    	if (!get_category($cat->category_parent)) {
    		// do something with the category, like use it to create a new query_posts or something
    	}
    }

    is there no other way, seems wasteful (even if I don’t have that many categories). I’d rather select from the get go the right ones.

    How do you expect to know if a category has no parents if you do not look at it?
    🙂

    Use wp_list_categories function with ‘depth’ parameter. get_categories has this parameter too.

    <ul>
      <?php
        wp_list_categories('depth=1');
      ?>
    </ul>

    See, http://codex.wordpress.org/Template_Tags/wp_list_categories

    Unfortunately get_categories doesn’t have this depth parameter it seems. I can’t use wp_list_categories because I want to insert something between the level 1 categories and their child:

    * Cat 1
    – View All
    – Child 1
    – Child 2
    * Cat 2
    – View All
    – Child 3
    – Child 4

    The documentation for get_categories was a little sparse in terms of telling you what the returned properties of the category object were.

    So, I did print_r($cat) on the resultant categories. This was very handy. It told me that there is a parent property, that will have an ID of the parent category if there is one, and 0 if there is not one. Therefore, it was quite easy to add this bit of code at the top of my get_categories() loop to ignore non-top-level categories:

    if ($cat->parent > 0) { continue; }

    Here is the whole thing in an nutshell.

    foreach (get_categories() as $cat) {
    		if ($cat->parent > 0) { continue; }
    		[... and now do whatever you want with the wanted categories... ]
    	}
Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Listing only top categories’ is closed to new replies.