side-menu.php
1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php /**
* Use wp_list_pages() to display parent and all child pages of current page.
*/
function wpse_get_ancestor_tree() {
// Bail if this is not a page.
if ( ! is_page() ) {
return false;
}
// Get the current post.
$post = get_post();
/**
* Get array of post ancestor IDs.
* Note: The direct parent is returned as the first value in the array.
* The highest level ancestor is returned as the last value in the array.
* See https://codex.wordpress.org/Function_Reference/get_post_ancestors
*/
$ancestors = get_post_ancestors( $post->ID );
// If there are ancestors, get the top level parent.
// Otherwise use the current post's ID.
$parent = ( ! empty( $ancestors ) ) ? array_pop( $ancestors ) : $post->ID;
// Get all pages that are a child of $parent.
$pages = get_pages( [
'child_of' => $parent,
] );
// Bail if there are no results.
if ( ! $pages ) {
return false;
}
// Store array of page IDs to include latere on.
$page_ids = array();
foreach ( $pages as $page ) {
$page_ids[] = $page->ID;
}
// Add parent page to beginning of $page_ids array.
array_unshift( $page_ids, $parent );
// Get the output and return results if they exist.
$output = wp_list_pages( [
'include' => $page_ids,
'title_li' => false,
'echo' => false,
] );
if ( ! $output ) {
return false;
} else {
return '<ul class="side-menu ancestor-tree">' . PHP_EOL .
$output . PHP_EOL .
'</ul>' . PHP_EOL;
}
}