get_post_ancestors()


WordPressのget_post_ancestors()関数は、特定の投稿またはページの祖先を取得するために使用されます。

構文

get_post_ancestors( int|WP_Post $post );
  • $post (int|WP_Post) — 投稿IDまたはWP_Postオブジェクト。取得する祖先の対象。

返り値:

  • array — 祖先の投稿IDを格納した配列。

例 1: 投稿の祖先を取得

特定の投稿の祖先IDを取得して表示します。

<?php
$post_id = get_the_ID();
$ancestors = get_post_ancestors( $post_id );
print_r( $ancestors );
?>

例 2: ルート祖先を取得

ルート祖先(最上位の親)のIDを取得します。

<?php
$post_id = get_the_ID();
$ancestors = get_post_ancestors( $post_id );
$root_ancestor = !empty( $ancestors ) ? end( $ancestors ) : null;
echo $root_ancestor;
?>

例 3: 親投稿のタイトルを取得

直近の親投稿のタイトルを取得します。

<?php
$post_id = get_the_ID();
$ancestors = get_post_ancestors( $post_id );
if ( !empty( $ancestors ) ) {
    $parent_id = $ancestors[0];
    echo get_the_title( $parent_id );
}
?>

例 4: 投稿の階層をリスト表示

祖先と現在の投稿を階層リストとして表示します。

<?php
$post_id = get_the_ID();
$ancestors = array_reverse( get_post_ancestors( $post_id ) );
array_push( $ancestors, $post_id );
foreach ( $ancestors as $ancestor_id ) {
    echo get_the_title( $ancestor_id ) . ' > ';
}
?>

例 5: ページテンプレートでの使用

特定の親ページがある場合にテンプレートを変更します。

<?php
$post_id = get_the_ID();
$ancestors = get_post_ancestors( $post_id );
if ( in_array( 42, $ancestors ) ) {
    include( 'template-specific-parent.php' );
} else {
    include( 'template-default.php' );
}
?>

注意点

  • この関数は階層構造の投稿タイプでのみ機能します(例: ページやカスタム投稿タイプ)。
  • $postが無効な場合、空の配列が返されます。

関連機能: