Working with titles, sub titles and parent titles in WordPress

In a range of WordPress sites I’ve been working recently there has been the need to use page titles in a non-standard WordPress way. In this tutorial I will demonstrate some ways to use page and post titles outside of the loop, including a subtitle on a page and show the parent page title.

Standard WordPress Page Titles

Let’s just start with how WordPress adds a page title by default when inside the loop. (If you’re not familiar with the loop read more on WordPress Codex.)

<h1><?php the_title(); ?></h1>

Putting the Post title outside the loop

If you need to put your title outside the loop you will first need to call  global $wp_query and then query your post using $thePostID = $wp_query->post->ID. Now that you have queried and found your posts ID you can use the get_the_title($thePostID) WordPress function to return your page title. All together it looks like this:

<?php global $wp_query; ?>
<?php $thePostID = $wp_query->post->ID; ?>
<h1><?php echo get_the_title($thePostID); ?></h1>

Including a sub title

To include a sub title you can use a custom field. To get the value of the custom field you use get_post_meta($post_id, $key, $single). I’ve added this to the previous example, just checking that the custom field has been set before outputting it to the page. On the pages I wished to include a sub heading I added a custom field called ‘page_subtitle’.

<?php global $wp_query; ?>
<?php $thePostID = $wp_query->post->ID; ?>
<?php $subTitle = get_post_meta($thePostID, 'page_subtitle', true); ?>

<h1><?php echo get_the_title($thePostID); ?></h1>
<?php if($subTitle) { ?>
  <h2><?php echo $subTitle; ?> </h2>
<?php } ?>

Including the parent title for child pages

Finally lets show how to display the name of the parent page. All you need to do is call get_the_title($post->post_parent). If a parent page doesn’t exists the output will just be blank. So you may want to check it’s returned a value before adding to your template.

<?php global $wp_query; ?>
<?php $thePostID = $wp_query->post->ID; ?>
<?php $subTitle = get_post_meta($thePostID, 'page_subtitle', true); ?>
<?php $parentTitle = get_the_title($post->post_parent);

<h1>
<?php if($parentTitle) {
   echo $parent_title." : ";
} ?>
<?php echo get_the_title($thePostID); ?>
</h1>
<?php if($subTitle) { ?>
  <h2><?php echo $subTitle; ?></h2>
<?php } ?>

The final output will look something like:

Parent Page : The Page
Subtitle