WordPress: How to get all sub categories id and add the parent category’s ID to the new array?

I want to get all the sub categories’ ID and add all the sub cat IDs and the parent ID to a new array?

For example:
Parent $ID=1
sub cat 1 :11
sub cat 2 :12
sub cat 3 :13
sub cat 4 :14

Read More

$arr = array(11,12,13,14)

The result: $arr2 = array(1,11,12,13,14) // add parent ID to the array.

$categories=get_categories($ID);

Then I don’t know what to do, please help me to solve the problem. Thanks.

Related posts

Leave a Reply

1 comment

  1. 1.) get_all_category_ids() will retrive all the category IDS. it returns an array containing both the child and parent category ID’es.

    2.) If you want to get it for a particular category: (Note: it will include all the child/child*n as well)

     //$pid = parent category id
    $Result = array_merge(array_diff(explode('/',get_category_children($pid)),array("")),array($pid));
    

    3.) if you want only the immediate child categories: ie: parent/child and not parent/child/child*n

                //$pid = parent category id;         
                $child_cats=array();
    
                foreach(get_all_category_ids() as $cat)
                {
                    if(get_category($cat)->parent==$pid)
                    {
                        $child_cats[]=$cat;
                    }
                }
    
                $result = array_merge($child_cats,array($pid));