WordPress - 在第3级子页面上列出多级父页面

时间:2009-07-21 15:44:22

标签: wordpress wordpress-theming

我目前正在网站上工作,导航的工作方式如下(根据客户规格)。

在标题下方有一个列出顶级页面的水平导航,单击其中一个会将您带到page.php,其侧栏中有一个垂直导航,列出该特定页面的子页面,如下所示: / p>

第二级 - 第3级 - 第3级 - 第3级 第二级 - 第3级 - 第3级 - 第3级

依此类推,等等。

这是我目前在垂直导航中使用的代码:

$children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
if ($children)
{
    <ul>
        echo $children;
    </ul>
}

我希望能够做的是继续使用相同的垂直导航,无论当前页面级别如何。当你在3级页面上时,我发现很难列出第1级页面的子页面。

任何建议都非常感谢。

3 个答案:

答案 0 :(得分:3)

尝试使用get_post_ancestors。在类似的情况下,这种方法似乎对我有用:

<?php
global $wp_query;
$post = $wp_query->post;
$ancestors = get_post_ancestors($post);
if( empty($post->post_parent) ) {
    $parent = $post->ID;
} else {
    $parent = end($ancestors);
} 
if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) { ?>

<ul id="secondary-nav">
    <?php wp_list_pages("title_li=&child_of=$parent&depth=1" ); ?>
</ul><!-- #secondary-nav -->

<?php } ?>

然后我用它来用CSS定位当前导航状态:

#secondary-nav li a:hover,
#secondary-nav li.current_page_item a,
#secondary-nav li.current_page_ancestor a {
    background:#fcb701;
}

您可能需要移除深度参数才能显示第3级页面。

我希望这有帮助!

答案 1 :(得分:0)

我认为这可以帮到你。我有同样的问题。我必须在子页面中显示父页面的布局内容(所有内容)。

add_action('wp_head', 'init_stuffs');
function init_stuffs(){
  if( is_page() ){
    $parents = get_ancestors(get_the_id(), 'page');
    if( count( (array) $parents ) >= 2 ){
      //now you can use $parents[1] as parent
      registry()->setParentPageId($parents[1]);
    }
  }
}

在我的情况下,我不得不加载父母的模糊。我使用Wordpress Registry插件来存储$ parents [1] id。然后我通过简单地在获取blurbs数据的函数中传递父页面id来获取父母的模糊。

function fetchBlurbs($parentId = null){
  if(is_null($parentId)){
    //fetch blurb for the page
  }else{
    //fetch blurb of parent page
  }
}

答案 2 :(得分:0)

一旦进入The Loop,就可以很容易地提取所有页面祖先的反向历史记录。

<?php
    // It's not necessary to globalize $post if you're doing this inside your page.php
    // but if you're in, say, sidebar.php, then you need to declare the global variable
    global $post;

    // We have to reverse the array so the top link is the topmost ancestor
    $history = array_reverse( array_map( 'get_post', get_post_ancestors( $post ) ) );

    // And if you want to add this page to the list as well, push it onto the end
    $history[] = $post;
?>

<ol>
<?php
    // Now, loop through each page in the list
    foreach( $history as $page ){
         echo "<li><a href='" . get_permalink( $page->ID ) . "' />" . get_the_title( $page ) . '</a>';
    }
?>
</ol>

关键路线当然是$history = array_reverse( array_map( 'get_post', get_post_ancestors( $post ) ) );这有两件事:

  1. 它将get_post_ancestors()返回的ID映射到实际WP_Post个对象(这不是必需的,因为我们真正需要的是要传递给get_permalink()和{{1}的ID }})
  2. 它会反转数组顺序,因为get_the_title()会将直接父级置于列表的顶部,我们可能希望它位于底部。
相关问题