Forums

[resolved] How do I get the category children without getting the children of children? (4 posts)

  1. bechster
    Member
    Posted 5 months ago #

    Hi,

    I'm trying to make a theme which shows an overview of child categories with title, link and description when entering a category archive. However, I only want to show child categories one level below the current category, and not the children of child categories. How do I do that?

    I've tried the following:

    $childcategories = get_categories('child_of=' . $cat . '&hide_empty=1');
    foreach ($childcategories as $childcategory) {
      if (in_category($childcategory)) {
        echo '<li><h2><a href="';
        bloginfo('url');
        echo '/category/'.$cat_id->category_nicename.'/'.$childcategory->category_nicename.'">';
        echo $childcategory->cat_name . '</a></h2>';
        echo '<p>'.$childcategory->category_description.'</p>';
        echo '<p>'.$childcategory->cat_ID.'</p>';
        echo '</li>';
      }
    }

    ... which seems to work perfectly in MAMP for mac but fails in XAMPP for win as well as on my debian server.

    What am I doing wrong? Can anybody help?

    Thanks in advance.

  2. MichaelH
    moderator
    Posted 5 months ago #

    See if the depth=n argument works. If works for wp_list_categories so guessing it might work for get_categories.

  3. bechster
    Member
    Posted 5 months ago #

    Thanks for the tip, however it didn't work.

  4. bechster
    Member
    Posted 5 months ago #

    mthomps found the solution: http://wordpress.org/support/topic/223988?replies=9#post-1054625

    I ended up with this piece of code, which works as intended:

    <?php
    global $ancestor;
    $childcats = get_categories('child_of=' . $cat . '&hide_empty=1');
    foreach ($childcats as $childcat) {
      if (cat_is_ancestor_of($ancestor, $childcat->cat_ID) == false){
        echo '<li><h2><a href="'.get_category_link($childcat->cat_ID).'">';
        echo $childcat->cat_name . '</a></h2>';
        echo '<p>'.$childcat->category_description.'</p>';
        echo '</li>';
        $ancestor = $childcat->cat_ID;
      }
    }
    ?>

Reply

You must log in to post.

About this Topic