Get all children page ID’s including parent by title

So I am getting all the children ID’s as well as the parent ID to show content only for that page and all its sub-pages. This is the following function I created, but was wondering if there is a better way to do it?

function get_all_pages( $page_title ) {

    $page = get_page_by_title( $page_title );

    $pages = get_pages( array( 'child_of' => $page->ID, 'sort_column' => 'post_date', 'sort_order' => 'desc' ) );

    $array = array();

    $array[] = array( 'ID' => $page->ID );

    foreach( $pages as $page ){

        $array[] = array( 'ID' => $page->ID );

    }

    return $array;

}

$allpages = get_all_pages( 'Page Title' );

foreach( $allpages as $page ) {

    if( is_page( $page['ID'] ) ):

        // Show stuff only on these pages

    endif;

}

Related posts

1 comment

  1. You have done this the hard way. WP_Query can do most of the work for you.

    function get_all_pages($page_title) {
      $page = get_page_by_title($page_title);
    
      if (empty($page)) return array();
    
      $children = new WP_Query(
        array(
          'post_type' => 'page',
          'post_parent' => $page->ID,
          'fields' => 'ids'
        )
      );
      array_unshift($children->posts,"{$page->ID}");
      return $children->posts;
    }
    
    $allpages = get_all_pages('Sample Page');
    var_dump($allpages);
    

    It is late, and I am sleepy, but I think that duplicates your function with the exception that your code, unnecessarily to my mind, produces nested arrays. My code gives you a “flat” array.

Comments are closed.