WordPress: Display Parent Page Title in the Title Tag

Recently we built a site where a large portion of the content was organized into sub-pages, each of which needed to display their parent page title in the template. After I finished building the site I realized that the parent page title should also be displayed in the <title> tag for SEO purposes. I had been using Yoast’s SEO plugin to display all my page titles in the following format:

<title>
  Page Title | Site Name
</title>

What I needed was for the top-level pages’ titles to stay the same while child pages’ titles to display like this:

<title>
  Parent Page Title — Page Title | Site Name
</title>

Since Yoast’s SEO plugin does not have a variable that can accomplish this, I had to edit my header.php template file and change this:

<title>
  <?php wp_title( '|', true, 'right' ); ?>
</title>

To this:

<title> 
 <?php 
   if($post->post_parent) { 
     $parent_title = get_the_title($post->post_parent); 
     echo $parent_title.' - '; 
   } 
  ?> 
 <?php wp_title( '|', true, 'right' ); ?> 
</title>

Display a child page’s parent page title in your title tag by copying and pasting the above code into your header.php template file.

0