2

我目前正在一个网站上工作,导航工作如下(按客户规范)。

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

二级 - 三级 - 三级 - 三级 二级 - 三级 - 三级 - 三级

等等等等。

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

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

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

任何建议都非常感谢。

4

3 回答 3

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 级页面。

我希望这有帮助!

于 2009-10-18T04:20:26.837 回答
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. 它将返回的 ID 映射get_post_ancestors()到实际WP_Post对象(这不是绝对必要的,因为我们真正需要的是传递给get_permalink()and的 ID get_the_title()
  2. 它颠倒了数组顺序,因为get_post_ancestors()将直接父级放在列表的顶部,我们可能希望它在底部。
于 2013-11-24T20:43:01.980 回答
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。然后我通过在获取简介数据的函数中简单地传递父页面 id 来获取父母的简介。

function fetchBlurbs($parentId = null){
  if(is_null($parentId)){
    //fetch blurb for the page
  }else{
    //fetch blurb of parent page
  }
}
于 2012-04-12T10:31:20.133 回答