WordPress tutorials: Check parent ID

Wpsnipp – This code checks if the page we’re on (current page) has a parent. If so, that means that we are at least 2 levels deep in the navigation. In that case function get_post_ancestors is called. It returns an array of all the ancestors’ IDs up to the top level (root).

 

 

<?
if ($post->post_parent) {
$ancestors=get_post_ancestors($post->ID);
$root=count($ancestors)-1;
$parent = $ancestors[$root];
} else {
$parent = $post->ID;
}
?>

Leave a comment