0

I'm building a query to get the child's child categories. For example : I have a parent category named 'animal' and others like 'food' and 'sport'. I want to get animal's sub categories.

I do :

$parent_cat = get_cat_ID( $cat_name );
$args = array(
    'type'      => 'post',
    'parent'    => $parent_cat,
    'order'     => 'DESC'
);
$categories = (array) get_categories( $args );

And no problem, with a foreach I get my animal's sub categories.

In my sub categories, I also have categories (this is a 3 levels hierarchy).

I do the same :

$child_cat = get_cat_ID( $sub_cat_name );
$args = array(
    'type'      => 'post',
    'parent'    => $child_cat,
    'order'     => 'DESC'
);
$sub_categories = (array) get_categories( $args );

And... it returns the others parents categories 'food' an 'sport'.

Why that ? Where am I wrong ?

2
  • Check this post Commented Jun 26, 2014 at 16:53
  • 1
    If you're getting top level categories, then the value of $child_cat is not what you think it is. make sure $sub_cat_name contains the correct name and that $child_cat is not 0.
    – Milo
    Commented Jun 26, 2014 at 17:44

1 Answer 1

0

Ok then, I actually was getting the subcats with the wrong method.

in $parent_cat = get_cat_ID( $cat_name ); $cat_name wasn't a name but un slug. First mistake.

So I corrected with $parent_cat = get_category_by_slug( $cat_slug );

The final code is :

// Get the parent cat thanks to the page's cat slug
$parent_cat = get_category_by_slug( $cat[1] );
$args = array(
    'type'      => 'post',
    'parent'    => $parent_cat->term_id,
    'order'     => 'DESC'
);
// child cats
$categories = get_categories( $args );
// loop on the child cats to get the sub cats object
foreach ($categories as $key => $value) {
    return $value;
}

That's it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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