描述:
获取所有的父页面
用法:
<?php get_post_ancestors( $post ) ?>
参数:
$post
(mixed) (必填) 文章 ID
默认值: None
示例:
此示例返回层级最高的页面{slug},并将其用作Body_Class,因此父级和所有子级将具有相同的Body_Class!
<?php
/* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
$class = '';
/* is it a page */
if( is_page() ) {
global $post;
/* Get an array of Ancestors and Parents if they exist */
$parents = get_post_ancestors( $post->ID );
/* Get the top Level page->ID count base 1, array base 0 so -1 */
$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
/* Get the parent and set the $class with the page slug (post_name) */
$parent = get_post( $id );
$class = $parent->post_name;
}
?>
<body <?php body_class( $class ); ?>>
源文件:
/**
* Retrieve ancestors of a post.
*
* @since 2.5.0
*
* @param int|WP_Post $post Post ID or post object.
* @return array Ancestor IDs or empty array if none are found.
*/
function get_post_ancestors( $post ) {
$post = get_post( $post );
if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
return array();
$ancestors = array();
$id = $ancestors[] = $post->post_parent;
while ( $ancestor = get_post( $id ) ) {
// Loop detection: If the ancestor has been seen before, break.
if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
break;
$id = $ancestors[] = $ancestor->post_parent;
}
return $ancestors;
}