Print Post Parent Title

I’m trying to print the posts’ parent title on the page as well as the post title for that page. This is how my content-page.php template currently renders the page title.

the_title( '<header class="entry-header"><h1 class="entry-title">', '</h1></header><!-- .entry-header -->' );

I realise I can retrieve the posts’ parent title by doing this:

Read More
$parent_title = get_the_title($post->post_parent);
echo $parent_title;

Is there anyway I can slip that code in between the_title parameters, so my parent title and my post title are both wrapped by that h1 element?

Any help is appreciated. Thanks in advance!

Related posts

Leave a Reply

3 comments

  1. You can just add a check:

    if ( ! empty ( $post->post_parent ) )
    {
        $parent_title = get_the_title($post->post_parent);
        echo "<h1>$parent_title</h1>";
    }
    

    or use setup_postdata():

    setup_postdata( $post->post_parent );
    the_title( /* arguments here*/ );
    wp_reset_postdata();
    
  2. I would just filter the_title:

    function wpse140502_filter_page_title( $title ) {
        // only do something on static pages
        // and on the main query
        if ( is_page() && is_main_query() ) {
            // let's see if the current page has a parent
            global $post;
            if ( 0 != $post->post_parent ) {
                // Set this to whatever you want
                $delimiter = ': ';
                // Append post-parent title to title and return it
                return get_the_title( $post->post_parent ) . $delimiter . $title;
            }
        }
        // return title
        return $title;
    }
    add_filter( 'the_title', 'wpse140502_filter_page_title' );
    
  3. You could just output the header around the title without using the $before and $after parameters:

    if ( get_the_title() ) {
        global $post;
    
        echo '<header class="entry-header"><h1 class="entry-title">';
        echo get_the_title() . ' - ' . get_the_title( $post->post_parent );
        echo '</h1></header>';
    }
    

    If you insist on using $before and $after, just pass the parent title to either one of the arguments:

    the_title( '<header class="entry-header"><h1 class="entry-title">' . get_the_title( $post->post_parent ), '</h1></header><!-- .entry-header -->' );
    

    or

    the_title( '<header class="entry-header"><h1 class="entry-title">', get_the_title( $post->post_parent ) . '</h1></header><!-- .entry-header -->' );