How can I retrieve a list of a Wordpress page's sibling pages?

后端 未结 4 1909
忘了有多久
忘了有多久 2021-02-19 04:08

I am trying to create a list of sibling pages (not posts) in WordPress to populate a page\'s sidebar. The code I\'ve written successfully returns a page\'s parent\'s title.

相关标签:
4条回答
  • 2021-02-19 04:42

    $post->post_parent is giving you the parent ID, $post->ID will give you the current page ID. So, the following will list a page's siblings:

    wp_list_pages(array(
        'child_of' => $post->post_parent,
        'exclude' => $post->ID
    ))
    
    0 讨论(0)
  • 2021-02-19 04:51

    Some of the answers on this page have slightly outdated info. Namely, exclude no longer seems to be needed when using child_of.

    Here's my solution:

    // if this is a child page of another page,
    // get the parent so we can show only the siblings
    if ($post->post_parent) $parent = $post->post_parent;
    // otherwise use the current post ID, which will show child pages instead
    else $parent = $post->ID;
    
    // wp_list_pages only outputs <li> elements, don't for get to add a <ul>
    echo '<ul class="page-button-nav">';
    
    wp_list_pages(array(
        'child_of'=>$parent,
        'sort_column'=>'menu_order', // sort by menu order to enable custom sorting
        'title_li'=> '', // get rid of the annoying top level "Pages" title element
    ));
    
    echo '</ul>';
    
    0 讨论(0)
  • 2021-02-19 04:53
    wp_list_pages(array(
        'child_of' => $post->post_parent,
        'exclude' => $post->ID,
        'depth' => 1
    ));
    

    The correct answer, as both other answers don't exclusively display the siblings.

    0 讨论(0)
  • 2021-02-19 04:56
    <?php if($post->post_parent): ?>
    <?php $children = wp_list_pages('title_li=&child_of='.$post->post_parent.'&echo=0'); ?>
    <?php else: ?>
    <?php $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0'); ?>
    <?php endif; ?>
    <?php if ($children) { ?>
    <ul class="subpage-list">
    <?php echo $children; ?>
    </ul>
    <?php } ?>
    

    Don't use the exclude parameter, just target that .current_page_item to differentiate.

    0 讨论(0)
提交回复
热议问题