get_post_ancestors()

get_post_ancestors( int|WP_Post $post )

检索帖子的祖先的 ID,即找到页面最顶级的页面。

参数

$post(int|WP_Post) (Required) Post ID or post object.

返回

(int[]) Array of ancestor IDs or empty array if there are none.

例子

找到最顶层父页面的 ID,如果你的页面结构有多层级,下面的代码可以找到某个页面最顶层的父页面 ID:

<?php
if ($post->post_parent)	{
	$ancestors	= get_post_ancestors($post->ID);
	$root		= count($ancestors)-1;
	$parent		= $ancestors[$root];
} else {
	$parent		= $post->ID;
}
?>

获取顶级页面缩略图并显示出来!

<?php
global $post;
$parents = get_post_ancestors( $post );
$id = $post->ID;
/* Get the ID of the 'top most' Page */
if ( ! empty( $parents ) ) {
    $id = array_pop( $parents );
}
if ( has_post_thumbnail( $id ) ) {
    echo get_the_post_thumbnail( $id, 'thumbnail' );
}
?>

获取祖先页面 Slug

此示例返回树中最高的页面 {slug} 并将其用作 Body_Class,因此父级和所有子级将具有相同的 Body Class!

此示例为 header.php 文件中的 twentyeleven 个子主题

<?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 ); ?>>

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注