Jump to content

Wordpress Php: List Of Parent An Children In Sidebar


Recommended Posts

Hi there!


I am currently trying to edit a wordpress theme, and with my limited knowledge, I got stuck first thing., I have just added a subpage to a page on my blog for the first time, and would love to display a list in the sidebar on the parent that displays the parent itself, and all children. On the childpages, this same list (parent+children) should be visible.


So, let's say I have a page called: contact, with subpages like 'route' and 'form', it should look like this, on the parentpage (contact) and the children:






On pages that do not have children, there should be no list.


Looking through the wordpress codex, I found the following code to add to my sidebar.php:

//if the post has a parent
 //collect ancestor pages
 $relations = get_post_ancestors($post->ID);
 //get child pages
 $result = $wpdb->get_results( "SELECT ID FROM wp_posts WHERE post_parent = $post->ID AND post_type='page'" );
 if ($result){
   foreach($result as $pageID){
     array_push($relations, $pageID->ID);
 //add current post to pages
 array_push($relations, $post->ID);
 //get comma delimited list of children and parents and self
 $relations_string = implode(",",$relations);
 //use include to list only the collected pages.
 $sidelinks = wp_list_pages("title_li=&echo=0&include=".$relations_string);
 // display only main level and children
 $sidelinks = wp_list_pages("title_li=&echo=0&depth=1&child_of=".$post->ID);

if ($sidelinks) { ?>
 <h2><?php the_title(); ?></h2>
   <?php //links in <li> tags
   echo $sidelinks; ?>
<?php } ?>

This works perfect on a child page, displaying child and parent in a neat linkable list. But on the parent page it only displays the child. How can I also add the parent there?


Thank you in advance for your help!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.