get_post_ancestors()
最后更新于:2021-11-26 22:27:28
get_post_ancestors( int|GC_Post$post)Retrieves the IDs of the ancestors of a post.
参数
- $post
-
(int|GC_Post) (Required) Post ID or post object.
响应
(int[]) Array of ancestor IDs or empty array if there are none.
源文件
文件: gc-includes/post.php
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 = $post->post_parent;
$ancestors[] = $id;
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, true ) ) {
break;
}
$id = $ancestor->post_parent;
$ancestors[] = $id;
}
return $ancestors;
}
</head> <?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 ); ?>>
</head> <?php $class = ''; if( is_page() ) { global $post; $parents = get_post_ancestors( $post->ID ); $id = ($parents) ? $parents[count($parents)-1]: $post->ID; $class = get_post_meta( $id, 'body_class', true ); } ?> <body <?php body_class( $class ); ?>>