I'm trying to get all direct child categories in category hierarchy.

What I've tried:

$args = array(
        'child_of' => get_query_var("cat")
$categories = get_categories($args);
foreach($categories as $category) {
    $catID = $category->cat_ID;
    $test = "cat_ID: " . $category->cat_ID . " " . "parent: " . $category->parent . ", "; 
    echo $test;

In caseget_query_var("cat") == 14 I get the following result:

cat_ID: 35 parent: 14, cat_ID: 34 parent: 14, cat_ID: 36 parent: 34, cat_ID: 37 parent: 34,

which is not what I want because this displays child's child categories. So I tried

$args = array(
        'parent' => strval(get_query_var("cat"))

which results in

cat_ID: 35 parent: 14,

instead of what I expected

cat_ID: 35 parent: 14, cat_ID: 34 parent: 14,

So what's going wrong?

  • parent only fetch the direct descendant of the parent category ID Are you child category at same level? Sep 8 '14 at 10:34
  • I think so. please see the first result using 'child_of' => get_query_var("cat") as filter where there are two results with 14 as parent
    – RTasche
    Sep 8 '14 at 10:39
  • What is your category structure? Sep 8 '14 at 10:40

To get direct descendants (i.e. children only) of the category, you need to make use of the parent parameter in get_categories()

The reason why you might not see your other category is that it does not have any posts assigned to it. To display empty categories, you need to set the hide_empty parameter to 0

Otherwise I do not see any problems with your code. You should also turn on debugging to check if you maybe have some kind of error if the above does not work

  • hide_empty brought the solution! I'm still confused why hide_empty has an effect on the 'parent' but not on the 'child_of' filter...
    – RTasche
    Sep 8 '14 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.