Forums

[resolved] PHP code to get current parent and all child pages? (7 posts)

  1. Matija Erceg
    Member
    Posted 1 year ago #

    I am trying to echo a list of links to the current parent and child pages. So, regardless if I'm in a top level page or a sub level page, I want to get the current Top and all Child pages and output them as links.

    I am using the Exec-PHP plugin and was thinking of doing this in a Text Widget.

    Is there a clean way to get all the current parent's children? Something like <?php get_page_children( $page_id=5, $pages )?> only gets the children of a particular parent. I would like to get the parent+children regardless where you are within those pages.

  2. Matija Erceg
    Member
    Posted 1 year ago #

    Is there a better place to try to get help with this question?

  3. ClaytonJames
    Member
    Posted 1 year ago #

  4. ClaytonJames
    Member
    Posted 1 year ago #

    I am trying to echo a list of links to the current parent and child pages.

    with heading

    <?php wp_list_pages('title_li=<h2>Pages</h2>' ); ?>

    without heading

    <?php wp_list_pages('title_li='); ?>

    style to suit.

  5. ClaytonJames
    Member
    Posted 1 year ago #

    I just tested this using Exec-PHP and a text widget per your above idea.
    This code - <?php wp_list_pages('title_li=<h2>Pages</h2>' ); ?> - placed in a text widget, showed the title "Pages", and listed all of my parent and child pages. Hope that puts you on the right track.

  6. Matija Erceg
    Member
    Posted 1 year ago #

    Thank you.

    After looking into this issue for a while, this is the code I've ended up using:

    <ul style="list-style-image:none;">
    <?php
      $ancestors = get_post_ancestors($post->ID);
      $parent = $ancestors[0];
    
      if($parent) { //if its a CHILD page
        echo wp_list_pages("title_li=&include=".$parent."&echo=0");
        $children = wp_list_pages("title_li=&child_of=".$parent."&echo=0");
    
    }  else { //if it's a PARENT page
        echo wp_list_pages("title_li=&include=".get_the_ID()."&echo=0");
        $children = wp_list_pages("title_li=&child_of=".get_the_ID()."&echo=0");
    }
      if ($children) { ?>
    
      <?php echo $children; ?>
      </ul>
      <?php } ?>

    This is assuming there is only 2 depths of link: the main pages, and 1 level of child pages

  7. JTWilcox
    Member
    Posted 1 year ago #

    This code is great. One question: What if you have one additional level? So main pages, 1 level of child pages, 1 level of child-child pages (or however you want to say it).

    Right now when I get to that lowest level, it only shows that level of pages, not any of the pages above it.

    Thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags