Displaying Parent & Child Pages of Current Page in WordPress

Displaying Parent & Child Pages of Current Page in WordPress

Posted by Rainey

Finding the parent and child pages for any given page can be useful for many reasons.  One use case is creating a sidebar navigation for a section of pages in a website. Finding the children of a current page is fairly easy using wp_list_pages(). But, there is not builtin WordPress function to get the parent and children of any given page.

To make this happen we can add the following function to the functions.php page in the WordPress theme. This function is going to return the ID of our top level parent page.

function get_top_parent_page_id() {
 
    global $post;
 
    $ancestors = $post->ancestors;
 
    // Check if page is a child page (any level)
    if ($ancestors) {
 
        //  Grab the ID of top-level page from the tree
        return end($ancestors);
 
    } else {
 
        // Page is the top level, so use  it's own id
        return $post->ID;
 
    }
 
}

After the function has been created, we can place the following code in our sidebar, or anywhere we want the page list to appear.

<?php $parent_page = get_top_parent_page_id($post->ID); ?>
 
<ul>
<?php wp_list_pages("child_of=$parent_page&title_li="); ?>
</ul>

Here we are using the parent_page variable to store the ID of our top level parent page.  Then, the variable is using within WordPress’ wp_list_pages() to give us our list of parent and child pages.

The original function came from here.

Like what you are reading? Subscribe to receive monthly tips & updates!

A Monthly Roundup of Articles and a Sweet Deal

Get the latest tips, tricks, tutorials and freebies in your inbox once a monthly.

Join our growing community of front-end web developers and designers. We are constantly publishing new industry tips, tricks and tutorials to help you take your game to the next level. We are also going to include a freebie or deal on something cool each month. Enter your email below and you will only receive this email once a month, nothing else.

Subscribe to our mailing list

* indicates required


    Today in Web Design - Snippets, Tutorials, WordPress
    Tagged | , , ,