Get the children of the parent category

I’m trying to get all the children categories to display in this loop but I’m struggling with the code. This is what I have so far.

<?php $args=array('orderby' => 'name', 'order' => 'ASC');
    $categories=get_categories($args); 
    foreach ($categories as $cat) { ?>
    <dt><a href="#" class="customer-acquisitiontop" id="<?php echo $cat->slug; ?>" data-filter=".<?php echo $cat->slug; ?>"><h2><?= $cat->cat_name; ?></h2></a></dt>
    <dd><div class="services">
    <?= $categories=get_categories('parent'); ?> /*This should be the children of the parent category */
    </div>
    </dd>
<?php } ?>

Any help would be great

4

You can’t just pass the string “parent” to get_categories. You have to pass the ID of the parent.

$categories=get_categories(
    array( 'parent' => $cat->cat_ID )
);

Notice that there are two similar but not equal “get child” parameters that you can use.

child_of
(integer) Display all categories that are descendants (i.e. children & grandchildren) of the category identified by its ID. There
is no default for this parameter. If the parameter is used, the
hide_empty parameter is set to false.

parent
(integer) Display only categories that are direct descendants (i.e. children only) of the category identified by its ID. This does
NOT work like the ‘child_of’ parameter. There is no default for this
parameter. [In 2.8.4]

Now you need to loop over the $categories. You can’t just echo an array.

foreach ($categories as $c) {
    var_dump($c);
    // what you really want instead of var_dump is something to
    // to create markup-- list items maybe, For example...
    echo '<li>'.$c->cat_name.'</li>';
}

Leave a Comment