Could anyone please tell me the code to display parent categories and their children along with their IDs?

I'd like to, for example, print them in this way:

Europe, United Kingdom, London (Europe is parent category, UK is child, London is child of UK)
102, 150, 175 (these are their relevant IDs)

Europe, France, Paris 102, 153, 189

Europe, France, Cannes 102, 153, 192

what i want to do is this: The steps I Followed (please check this link)

I only want to change this code:

<ul> <?php wp_list_categories('show_count=1&title_li=&hide_empty=0'); ?></ul>

so that the list of of all the categories and their childs will be displayed along with their ids in this format:

Example: Europe,United Kingdom,London, East Ham : 25,28,34,36 this is just one parent category (Europe) and its childs (Uk) the child of UK is London, and the child of london is East Ham. 25 is the id of Europe, 28 is the id of UK, 34 is the id of London, 36 is the id of East Ham

Please note: I just want to display this list on a page as described in the link above. Thank you so much

1 Answer 1


Are you looking for a list of the current post's categories and parents, or just a general list of categories? If the former, you can use get_category_parents(). If you're in The Loop, for example:

    if( have_posts() ) : 
        while( have_posts() ) :
            // Post stuff
            // ...

            $cats = wp_get_post_categories( $post->ID );
            foreach( $cats as $c ) {

                $category_list = ''; // initialize our text strings
                $category_id_list = '';

                $display = false;
                $sep = ', ';
                $nice = false;
                $parents = get_category_parents( $c, $display, $sep, $nice );

                $_parents = explode( ',', $parents ); // convert the string to an array
                $_parent_ids = array(); // initialize the array for the IDs
                foreach( $_parents as $p ) {
                    $_parent_ids[] = get_cat_ID( $p );
                // convert the $_parent_ids array to a string
                $parent_ids = implode( ', ', $_parent_ids );
                echo( "$parents $parent_ids" );


[Edited: Cleaned up the code, and took advantage of PHP's implode() function]

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.