Skip to content

Instantly share code, notes, and snippets.

@hissy
Last active October 5, 2015 22:18
Show Gist options
  • Save hissy/2886355 to your computer and use it in GitHub Desktop.
Save hissy/2886355 to your computer and use it in GitHub Desktop.
#WordPress Get Toplevel Ancestor Page
<?php
/**
* Returns top level ancestor page
*
* Usage: $toplevel = get_toplevel_ancestor_page(get_the_ID());
*
* @param int|object $post Post ID or post object. Optional, default is the current post from the loop.
* @return WP_Post|null WP_Post on success or null on failure
*/
function get_toplevel_ancestor_page( $post ) {
$post = get_post( $post );
if ( !$post || is_wp_error( $post ) )
return null;
if ( $post->post_parent ) {
$ancestors = get_post_ancestors( $post );
$root = count ( $ancestors ) - 1;
$parent = get_post( $ancestors[$root] );
} else {
$parent = $post;
}
return $parent;
}
@hissy
Copy link
Author

hissy commented Mar 24, 2014

Example: get and print top level ancestor's title

<?php
$ancestor = get_toplevel_ancestor_page();
echo get_the_title( $ancestor );
?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment