Get Page Hierarchy

If you have sequential content on your website using pages, you might need to know where in the section a user is, what page is before and what page is after. For instance, you might want to Previous/Next Page navigation like you would using get_previous_post() on posts.

This function will find all the pages in the current section and return an array containing the full list (an array of IDs in order), the previous page, and the next page.

<?php
/**
* Get Page Hierarchy
*
* returns array
* -- pages (all pages in order)
* -- prev (previous page)
* -- next (next page)
*
* @author Bill Erickson
* @link http://www.billerickson.net/code/get-page-hierarchy/
*/
function be_get_page_hierarchy() {
global $post;
$loop = new WP_Query( array(
'post_type' => 'page',
'post_parent' => $post->post_parent,
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
'fields' => 'ids',
) );
$output = array(
'pages' => $loop->posts,
);
foreach( $loop->posts as $k => $v ) {
if( $v == get_the_ID() ) {
if( isset( $loop->posts[$k-1] ) )
$output['prev'] = $loop->posts[$k-1];
if( isset( $loop->posts[$k+1] ) )
$output['next'] = $loop->posts[$k+1];
}
}
return $output;
}
view raw functions.php hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk