1

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:

$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!

3 Answers 3

2

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();
1

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' );
2
  • This filter is used on many places, including widgets and nav menus.
    – fuxia
    Apr 7, 2014 at 12:10
  • Let me fix that Apr 7, 2014 at 12:10
0

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 -->' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.