Show Page Title for All Pages Except Root Ancestor

I previously attempted this using post_parent, grandparent and ancestor information in an if statement, but I find this method is cleaner.

$post_id = $post->ID; //or somehow get the current post ID.
$ancestors = get_post_ancestors($post_id);
//$ancestors is an array of post IDs starting with the current post going up the root
//'Pop' the root ancestor out or returns the current ID if the post has no ancestors.
$root_id = (!empty($ancestors) ? array_pop($ancestors): $post_id);

if($post->ID === $root_id) {
	// when on root parent page, show nothing
} else { // all other pages, show page title ?>

    <h1 class="entry-title"><?php the_title(); ?></h1>    

<?php } ?>

Reference.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.