Search code examples
wordpress

List categories of page id an its children


Is it possible in WordPress to list the categories used by the children pages of a designated page ID.

So Page ID: 30 is the parent It has children pages which use the WP Categories.

Id like to list on page ID 30, all the categories that are used by all of the children of page ID 30.

I was hoping this was possible using get_categories but i cant seem to find any info about how to achieve it?


Solution

  • Yes, you can use the functions such as get_pages(), get_the_category(), and wp_list_categories().

    function list_child_page_categories_info( $parent_id ) {
        // Here we are getting all child pages of the parent page.
        $args = array(
            'post_type'      => 'page',
            'post_parent'    => $parent_id,
            'posts_per_page' => -1 // Get all children
        );
    
        $child_pages = get_pages($args);
    
        // Here we are initialize an array to store unique category IDs.
        $category_ids = array();
    
        // We are looping through each child page.
        foreach ( $child_pages as $page ) {
            // Here we are getting categories of the child page.
            $categories = get_the_category($page->ID);
    
            // Here we are storing each category ID ensuring there are no duplicates.
            foreach ( $categories as $category ) {
                if ( ! in_array( $category->term_id, $category_ids, true ) ) {
                    $category_ids[] = $category->term_id;
                }
            }
        }
    
        // Here we are displaying the categories.
        if ( ! empty( $category_ids ) ) {
            echo '<ul>';
            foreach ( $category_ids as $category_id ) {
                $category = get_category( $category_id );
                echo '<li>' . esc_html( $category->name ) . '</li>';
            }
            echo '</ul>';
        } else {
            echo 'No categories found for child pages.';
        }
    }
    
    // You can use the function.
    list_child_page_categories_info(30);