get_ancestors()


WordPressのget_ancestors()関数は、指定されたオブジェクト(投稿、ページ、カスタム投稿タイプ、タクシソノミーなど)の先祖(親、祖父など)のIDを取得するために使用されます。

構文

get_ancestors( int $object_id, string $object_type, string $resource_type );

引数の説明:

  • $object_id(int) — 先祖を取得したいオブジェクトのID。
  • $object_type(string) — オブジェクトのタイプ。例えば、’post’、’page’、’custom_post_type’など。
  • $resource_type(string) — リソースのタイプ。デフォルトは’post_type’ですが、’taxonomy’なども指定可能。

例1: ページの先祖IDを取得

この例では、現在のページの先祖IDを取得します。

<?php $ancestors = get_ancestors(get_the_ID(), 'page'); print_r($ancestors); ?>

例2: カスタム投稿タイプの先祖IDを取得

カスタム投稿タイプの先祖IDを取得する例です。

<?php $ancestors = get_ancestors(get_the_ID(), 'custom_post_type'); print_r($ancestors); ?>

例3: タクソノミーの先祖IDを取得

タクソノミーの先祖IDを取得する例です。

<?php $ancestors = get_ancestors(get_queried_object_id(), 'category', 'taxonomy'); print_r($ancestors); ?>

例4: 先祖IDをリスト表示

先祖IDをリスト形式で表示する例です。

<?php $ancestors = get_ancestors(get_the_ID(), 'page'); if (!empty($ancestors)) { echo '<ul>'; foreach ($ancestors as $ancestor) { echo '<li>' . $ancestor . '</li>'; } echo '</ul>'; } ?>

例5: 先祖ページのタイトルを表示

先祖ページのタイトルを表示する例です。

<?php $ancestors = get_ancestors(get_the_ID(), 'page'); if (!empty($ancestors)) { foreach ($ancestors as $ancestor) { echo get_the_title($ancestor) . '<br>'; } } ?>

例6: 先祖ページへのリンクを生成

先祖ページへのリンクを生成する例です。

<?php $ancestors = get_ancestors(get_the_ID(), 'page'); if (!empty($ancestors)) { foreach ($ancestors as $ancestor) { echo '<a href="' . get_permalink($ancestor) . '">' . get_the_title($ancestor) . '</a><br>'; } } ?>

例7: 先祖ページのスラッグを取得

先祖ページのスラッグを取得する例です。

<?php $ancestors = get_ancestors(get_the_ID(), 'page'); if (!empty($ancestors)) { foreach ($ancestors as $ancestor) { echo get_post_field('post_name', $ancestor) . '<br>'; } } ?>

例8: 先祖ページのカスタムフィールドを取得

先祖ページのカスタムフィールドを取得する例です。

<?php $ancestors = get_ancestors(get_the_ID(), 'page'); if (!empty($ancestors)) { foreach ($ancestors as $ancestor) { echo get_post_meta($ancestor, 'custom_field_key', true) . '<br>'; } } ?>

注意点

  • get_ancestors()は、指定されたオブジェクトの先祖IDを配列で返します。先祖がない場合は空の配列を返します。
  • オブジェクトタイプやリソースタイプを正しく指定しないと、期待した結果が得られない場合があります。
  • 大量のデータを扱う場合、パフォーマンスに影響を与える可能性があるため、注意が必要です。

関連機能: