Last active
October 5, 2015 22:18
-
-
Save hissy/2886355 to your computer and use it in GitHub Desktop.
#WordPress Get Toplevel Ancestor Page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: get and print top level ancestor's title