skip to Main Content

I am trying to get a list of child pages to display on the parent page via wordpress. The best way I can describe what I am trying to do is if you are on the about page (/about) but you want to go to the meet the team page (/about/meet-the-team) when you are on the about page it should then display a link to the meet the team page.

I have this code at the moment

function getPagesHierarchy() {
    $pagesQuery = new WP_Query(array(
        'post_type'     => 'page',
        'posts_per_page' => -1,
        'post_parent'   => 0,
        'order'         => 'ASC',
        'post_status'   => 'publish'
    )) ;
    if ($pagesQuery->have_posts()) {
        while($pagesQuery->have_posts()) {
            $pagesQuery->the_post() ;
            the_title() ;
            echo '<br>' ;
        }
    }
    
}

What this is doing is it is getting a structure of the parent pages like this image shows below
enter image description here

This is currently getting all the parent pages which is fine however I also need it to display that parent pages children under it. so for example it would be something like this;

enter image description here

Any help with this would be much appreciated if I can give anything else to assist in what I am trying to achieve please do let me know.

2

Answers


  1. You can use wp_list_pages() and pass in the parent page ID with child_of to get its children. You can refer to the WP docs for more info.
    So that’d look something like

    wp_list_pages(array(
        'child_of' => $parentId
    ));
    
    Login or Signup to reply.
  2. Probably best to use get_pages()

    function getPagesHierarchy() {
        
        $pages = get_pages(array('parent' => 0)); 
        foreach ( $pages as $page ) {
            echo $page->post_title;
            echo '<br>' ;
            $child_pages = get_pages(array( 'child_of' => $page->ID)); 
            foreach ( $child_pages as $child_page ) {
                echo $child_page->post_title;
                echo '<br>' ;
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search