You need to look at get_ancestors()
to get the top level parent of a page. Just a note, for reliability, use get_queried_object()
(or even better $GLOBALS['wp_the_query']->get_queried_object()
) to get the current post/page object on singular pages, $post
can be quite unreliable
You can try the following in your shortcode:
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
$parent = end( $ancestors );
}
$parent
will now always hold the top level parent of any given page
EDIT – from comments
If you need to get the page two levels higher than the current one, you can still use the same approach, but insted of using the last ID from `get_ancestors (which is the top level parent), we need to adjust this to get the second entry
Lets modify the code above slightly
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
// Check if $ancestors have at least two key/value pairs
if ( 1 == count( $ancestors ) ) {
$parent = $post->post_parent;
} esle {
$parent = $ancestors[1]; // Gets the parent two levels higher
}
}
LAST EDIT – full code
function wpb_list_child_pages_popup()
{
// Define our $string variable
$string = '';
// Make sure this is a page
if ( !is_page() )
return $string;
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
// Check if $ancestors have at least two key/value pairs
if ( 1 == count( $ancestors ) ) {
$parent = $post->post_parent;
} else {
$parent = $ancestors[1]; // Gets the parent two levels higher
}
}
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=" . $parent . "&echo=0' );
$string .= '<ul id="child-menu">' . $childpages . '</ul>';
return $string;
}
add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');