1

I have IDs for my child categories, 11,14,21,35,38,39, where these all are various child categories from their main category:

  • Parent category 1 has: 11,14
  • Parent category 2 has: 21
  • Parent category 3 has: 35,38,39

How can I group my child IDs as per their parent category, like below?

array(
    1 => array ( 11,14 ),
    2 => array ( 21 ),
    3 => array ( 35,38,39 )
)
2
  • Do you mean that you literally want array of IDs structured like that or something else? What are you trying to accomplish with it?
    – Rarst
    Dec 1, 2015 at 20:44
  • Yes, I want array of IDs structured like that and I can use those array to display some posts.
    – hkc
    Dec 1, 2015 at 20:50

2 Answers 2

1

The quick take would be something like this:

$categories        = [ ];
$parent_categories = get_categories( [ 'parent' => 0 ] );

foreach ( $parent_categories as $parent_category ) {
    $id                = $parent_category->term_id;
    $categories[ $id ] = wp_list_pluck( get_categories( [ 'parent' => $id ] ), 'term_id' );
}

The important bit is a parent argument, which limits retrieved to immediate children (parent of 0 is a top level).

Depending on how many of these you have it might be preferable to instead retrieve all of them first and then re-arrange out of singe result set.

4
  • I was looking to doing something like this. I was just short of wp_list_pluck function, I was not aware of it and was looking for it. We can use child_of instead of parent, in the wp_list_pluck to include its all descedant.
    – hkc
    Dec 1, 2015 at 21:36
  • One more thing, its making array of all the parent = > child array, I only need the array, for my given child cats IDs. How about that ?
    – hkc
    Dec 1, 2015 at 22:06
  • Pass them in include argument probably.
    – Rarst
    Dec 1, 2015 at 22:15
  • I have used array_intersect() to take out the matching value from this array. Thanks
    – hkc
    Dec 1, 2015 at 23:28
0

I had exactly same requirement as you. The below piece of code is my solution:

$termArr = array();
$termIds = array_filter(explode(',','11,14,21,35,38,39'),'is_numeric');
if( !empty($termIds) ){
    $terms = get_terms(array(
        'taxonomy' => 'my_taxonomy',
        'include' => $termIds
    ));

    foreach($terms as $t){
        if( !isset($termArr[$t->parent]) )
            $termArr[$t->parent] = array();
        $termArr[$t->parent][] = $t->term_id;
    }

    print_r($termArr); //===> This is the array which you need :)
}

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.