Using WordPress ‘get_post_ancestors()’ PHP function

The get_post_ancestors() WordPress PHP function retrieves the IDs of the ancestors of a post.

Usage

get_post_ancestors( $post )

Example:

Input: $post_id = 45;

Output: [ 32, 20, 12 ] (An array of ancestor IDs)

Parameters

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

More information

See WordPress Developer Resources: get_post_ancestors()

Examples

Display the top-level page thumbnail

This code displays the thumbnail of the top-level page in a hierarchy.

global $post;
$parents = get_post_ancestors($post);
$id = $post->ID;

if (!empty($parents)) {
    $id = array_pop($parents);
}

if (has_post_thumbnail($id)) {
    echo get_the_post_thumbnail($id, 'thumbnail');
}

Add a body class based on the top-level page slug

This code adds a body class based on the top-level page slug in a hierarchy.

$class = '';

if (is_page()) {
    global $post;
    $parents = get_post_ancestors($post->ID);
    $id = ($parents) ? $parents[count($parents) - 1] : $post->ID;
    $parent = get_post($id);
    $class = $parent->post_name;
}

<body <?php body_class($class); ?>>

Add a body class based on a custom field

This code adds a body class based on a custom field body_class from the top-level page in a hierarchy.

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

Retrieve the top-level page title

This code retrieves the top-level page title in a hierarchy.

global $post;
$parents = get_post_ancestors($post);

if (!empty($parents)) {
    $top_level_id = array_pop($parents);
    $top_level_page = get_post($top_level_id);
    echo $top_level_page->post_title;
}

Check if a post has a specific ancestor

This code checks if a post has a specific ancestor (e.g., ancestor with ID 32).

$ancestor_id = 32;
$parents = get_post_ancestors($post);

if (in_array($ancestor_id, $parents)) {
    echo 'This post has the specified ancestor.';
} else {
    echo 'This post does not have the specified ancestor.';
}