How to get child pages of a page in WordPress
Sometime while working in WordPress we need to fetch all child pages of a parent page. As we know that WordPress have the concept of child and parent pages. So, here we are discussing how to to achieve this.
First of all we should have the idea of creating child pages for a page. It is very simple, just look at the right section saying “Page Attributes” while adding a new page. There is a drop-down showing just below a text “Parent”. It is having complete list of already created pages. Just look at the image,it will give you exact idea for it.
As we know WordPress is a powerful CMS among all, it is a sign of a good developer if we are using its all features in a best possible manner to achieve our requirements. Below mentioned code is a simple and useful approach to get child pages of a parent page successfully.
Just use the below code:
<?php $args = array( 'post_type' => 'page', //write slug of post type 'posts_per_page' => -1, 'post_parent' => '26', //place here id of your parent page 'order' => 'ASC', 'orderby' => 'menu_order' ); $childrens = new WP_Query( $args ); if ( $childrens->have_posts() ) : ?> <?php while ( $childrens->have_posts() ) : $childrens->the_post(); ?> <div class="children" id="child-<?php the_ID(); ?>"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p><?php the_content(); ?></p> </div> <?php endwhile; endif; wp_reset_query(); ?>
In this way you will get titles and content for all the child pages. Don’t forgot to add your parent page id in above arguments. We have taking a dummy id that is “26”, replace it as per your need.
You can get the id of the all child pages inside the loop by using:
<?php the_ID(); ?>
This id will be helpfull to fetch other details of these child pages like their thumbnail images, categories etc. We have taken few minimum required parameters in argument, you can add few more as per your requirement. Just check other available arguments here at wordpress codex.
Feel free to ask your queries if any.