Skip to content

Instantly share code, notes, and snippets.

@hissy

hissy/gist:2886355

Last active Oct 5, 2015
Embed
What would you like to do?
#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

This comment has been minimized.

Copy link
Owner Author

@hissy 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
You can’t perform that action at this time.