Method 1: Using the WP_Query Class
The WP_Query class is a powerful tool in WordPress that can be used to query almost any type of content data, including pages and child pages. Here is an example code snippet demonstrating how to use WP_Query to retrieve all child pages under a specific parent page:
php<?php // Assuming $parent_page_id is the ID of the parent page $parent_page_id = 123; $args = array( 'post_type' => 'page', // Set to page type 'posts_per_page' => -1, // Retrieve all child pages 'post_parent' => $parent_page_id, // Set parent page ID 'order' => 'ASC', // Sort by publish date in ascending order 'orderby' => 'menu_order' // Sort by menu order ); $parent_query = new WP_Query($args); if ($parent_query->have_posts()) : while ($parent_query->have_posts()) : $parent_query->the_post(); // Output child page title or other information the_title(); endwhile; wp_reset_postdata(); endif; ?>
Method 2: Using the get_pages Function
The get_pages function is specifically designed for retrieving pages and is simpler to use compared to WP_Query, making it ideal for scenarios where only page data is needed. Here is how to use get_pages to retrieve all child pages of a parent page:
php<?php // Assuming $parent_page_id is the ID of the parent page $parent_page_id = 123; $args = array( 'child_of' => $parent_page_id, // Set parent page ID 'sort_column' => 'menu_order', // Sort by menu order 'sort_order' => 'asc' // Ascending order ); $pages = get_pages($args); foreach ($pages as $page) { // Output child page title or other information echo $page->post_title; } ?>
Summary
Both methods have their pros and cons: WP_Query is more powerful and flexible, allowing for more customizable query parameters, while get_pages is simpler and focused specifically on pages. When choosing the appropriate method, consider your specific requirements and scenarios. For example, if you need complex query conditions such as custom field filtering, WP_Query is the better choice; if you simply need to retrieve a list of child pages, get_pages can handle the task effectively.