Corentin Branquet
Corentin Branquet

Reputation: 1576

Get children pages Wordpress

I've this hierarchy in Wordpress :

- Page
    - Child 1
    - Child 2
    - Child 3
        - Subchild 1
        - Subchild 2
    - Child 4
- Page

What I want to do do is only display Subchild pages so I did this :

<?php 
     wp_list_pages( array(
        'child_of' => $post->ID,
        'depth' => 2 
        'sort_order' => 'asc'
    ));
?>

But it display all child pages and not only SubChild pages

Thanks for your help !

Upvotes: 2

Views: 6843

Answers (2)

Harshal Solanki
Harshal Solanki

Reputation: 21

/* Fetch only child from current page id*/    
             $pages = get_pages(
             array (
                      'parent'  => 'page_id', 
                      'post_type  => 'page', 
                      'post_status'  => 'publish',
                    );
                    
             $ids = wp_list_pluck( $pages, 'ID' );
     /* Return page IDs in array format */
     /* You can retrieve "post_title", "guid", "post_name" instead of "ID" */    

/* Fetch Child of child using page id */    
    $pages = get_pages(
             array (
             'parent'  => '-1',
             'child_of' => 'page_id', /* Return child of child for current page id */
             'post_type  => 'page',
             'post_status'  => 'publish',
              );
             $ids = wp_list_pluck( $pages, 'ID' );
    /* Return page IDs in array format */
    /* You can retrieve "post_title", "guid", "post_name" instead of "ID" */
    
    

Upvotes: 0

The M
The M

Reputation: 661

To display child pages based on a parent page i wrote this code:

In childArgs you give the parameters, the most import one is child_of, here i say i want all the pages from the page with this ID. You can use the get_the_ID() function or put a id from your page.

In $childList i use the get_pages function that returns all pages in an array from the specific page ID.

Than i use a foreach over the array that i got from get_pages function and than display the content & title. If you want to style the sub page individually i use post_class() function to give the subpage name as class to it.

<?php
      $childArgs = array(
          'sort_order' => 'ASC',
          'sort_column' => 'menu_order',
          'child_of' => get_the_ID()
      );
      $childList = get_pages($childArgs);
      foreach ($childList as $child) { ?>
        <!-- Generates all class names you would expect from a normal page. Example: page, post-{id} etc. -->
        <section <?php post_class($child->post_name); ?>>

        <h1><?php echo $child->post_title; ?></h1>


        <?php echo apply_filters( 'the_content', $child->post_content); ?>

        </section>  

    <?php } ?>

The result is: - Main page (show nothing) - subpage1 (show: title,content) - subppage2 (show: title,content)

Upvotes: 6

Related Questions