1

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;

}

1 Answer 1

2

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.

1
  • 1
    I actually had changed mine to produce a single dimension array, but your way is much cleaner! Appreciate the response. Forgot about just querying what I needed. Thanks! Commented Feb 26, 2014 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.