如何检索Wordpress页面的兄弟页面列表?

sjs*_*utt 12 wordpress wordpress-theming

我试图在WordPress中创建一个兄弟页面列表(而不是帖子)来填充页面的侧边栏.我写的代码成功返回页面的父级标题.

<?php
$parent_title = get_the_title($post->post_parent);
echo $parent_title; ?>
Run Code Online (Sandbox Code Playgroud)

据我所知,你需要一个页面的id(而不是标题)来检索一个页面的兄弟(通过wp_list_pages).如何获取页面的父级ID?

欢迎使用替代方法.目标是列出页面的兄弟姐妹,而不仅仅是检索父母的ID.

Ric*_*d M 26

$post->post_parent给你父ID,$post->ID会给你当前的页面ID.所以,下面将列出一个页面的兄弟姐妹:

wp_list_pages(array(
    'child_of' => $post->post_parent,
    'exclude' => $post->ID
))
Run Code Online (Sandbox Code Playgroud)


pbo*_*ond 15

wp_list_pages(array(
    'child_of' => $post->post_parent,
    'exclude' => $post->ID,
    'depth' => 1
));
Run Code Online (Sandbox Code Playgroud)

正确的答案,因为其他答案并不专门显示兄弟姐妹.


squ*_*ndy 8

此页面上的某些答案的信息略有过时。也就是说,exclude在使用child_of.

这是我的解决方案:

// 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>';
Run Code Online (Sandbox Code Playgroud)