进入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 ) ) );
这做了两件事:
- 它将返回的 ID 映射
get_post_ancestors()
到实际WP_Post
对象(这不是绝对必要的,因为我们真正需要的是传递给get_permalink()
and的 ID get_the_title()
)
- 它颠倒了数组顺序,因为
get_post_ancestors()
将直接父级放在列表的顶部,我们可能希望它在底部。