Print Parent Page Title if it Exists WordPress

Written by on October 1, 2012 in WordPress - No comments
wordpress-post-parent-title

It’s easy enough to print the current title of the page you’re on in WordPress.. but what if you want to print the page’s parent title before the current page title (to help users know what section they are in most likely)? Here is a little chunk of code I used recently.. basically the code says “if the page has a parent print that parent’s name and then the name of the current page, if it doesn’t have a parent just print the name of the current page”. The span isn’t needed, I was using that for styling purposes, keep or remove it if you want..

<h1 class="entry-title"> <?php
if($post->post_parent) {
	$parent_title = get_the_title($post->post_parent);
	echo $parent_title;
	echo ': ';
	echo '<span>';
	echo get_the_title($post->ID);
	echo '</span>';
	}
	else {				
	echo get_the_title($post->ID);
}
?></h1> 

Sponsors

About the Author

Mike Ilsley "ilz" is a Boston based website designer, front-end developer, WordPress addict, owner of Beantown Design, and exclusive ThemeForest author. Follow him on Twitter and Facebook, and don't forget to subscribe to the WebDesign&Such email RSS feed. Also, check out his latest project, jQueryMobileShowcase.com.