Skip to content

Instantly share code, notes, and snippets.

@aliharis
Last active August 29, 2015 14:07
Show Gist options
  • Save aliharis/ac5ce4857778c5ad4b25 to your computer and use it in GitHub Desktop.
Save aliharis/ac5ce4857778c5ad4b25 to your computer and use it in GitHub Desktop.
Display Wordpress pages in a hierarchical order
<?php
function getPagesInHierachy($post, $options = null) {
// default args for wp_list_pages (show only top level pages)
$args = array('depth' => 1);
if(is_page()) {
// get top level page ID from current page
$parents = get_post_ancestors( $post->ID );
$parent = ($parents) ? $parents[count($parents)-1]: $post->ID;
if (get_pages('parent=0')) {
$pageids = array();
foreach (get_pages('parent=0') as $page) {
$pageids[]= $page->ID;
// check page is the same as the top level page of the current page
if($page->ID == $parent) {
$children = get_pages('child_of='.$parent);
if($children) {
foreach ($children as $child) {
if($child->post_parent == $parent) {
$pageids[]= $child->ID;
}
if( in_array($child->post_parent,$parents)) {
$pageids[]= $child->ID;
}
if($child->post_parent == $post->ID) {
$pageids[]= $child->ID;
}
}
}
}
}
$pageids = array_unique($pageids);
// new args for wp_list_pages
$args = array('include' => $parent . ',' . implode(",", $pageids));
}
}
if (!empty($options)) $args = array_merge($args, $options);
return $args;
}
<?php
// Default
wp_list_pages(getPagesInHierachy($post));
// List wp pages with parameters
wp_list_pages(getPagesInHierachy($post, array('title_li' => '')));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment