0

I'm using a function to add conditional titles to the header of the html; example below.

add_filter('document_title_parts', 'change_wp_title', 20, 1);

function change_wp_title($title) {
global $post, $paged;
$grappig = $title;

// 404
if (is_404()) {
$title['title'] = 'file not available';
}

elseif (is_singular( 'schedule' )){
$title['title'] = 'Schedule: ' . $title['title'];
}

// Everything else.
else {
}
return $title;

}

I want to add the title of the parent page, so that a schedule page would have a title of 'Schedule: parent_title: post_title.

I know this isn't a free code-writing service, but I've searched extensively on this and have no idea how to do it.

1 Answer 1

0

You can get all parent post id by get_post_ancestors function.

add_filter( 'document_title_parts', 'change_wp_title', 20, 1 ); 

function change_wp_title( $title ) {

        global $post, $paged;

        $grappig = $title;

        // 404
        if ( is_404() ) {

            $title['title'] = 'file not available';

        } elseif ( is_singular( 'schedule' ) ) {

            // get all parent post's id
            $parents = get_post_ancestors( $post->ID );

            $parent_titles = 'Shedule: ';

            foreach ( array_reverse( $parents ) as $key => $parentpost )                   
            {
                  $postdata = get_post( $parentpost );
                  $parent_titles .= $postdata->post_title . ' : ';
            }

            $title['title'] = $parent_titles . $title['title'];

        } // End if().
        else {

        }
            return $title;
    }

Reference: get_post_ancestors

4
  • ...thanks. That's excellent. Having added it, I realize my original question is flawed... as pages get deeper in the hierarchy, I want to be able to include parents of parents of parents etcetera, similar to a breadcrumb. I assume that's using an 'ancestors' tag, about which I know little and am currently searching on. If you have any guidance on how your code can be adapted to include ancestors, please share if you're able. If not, thanks for your help so far. :-)
    – glvr
    Commented Nov 23, 2016 at 9:34
  • 1
    Please check edited code, mark as correct answer if it is helpful
    – GKS
    Commented Nov 23, 2016 at 9:46
  • thanks. yes, That's excellent. While I was drafting this comment, I think you modified the '$title['title'] = $parent_titles. $title['title'];' part of your code to include the '$title['title'];' which wasn't in the initial post. And I think '} elseif ( is_singular( 'page' ) ) {' needs 'page' replacing with 'schedule'. Thanks hugely. ;-)
    – glvr
    Commented Nov 23, 2016 at 10:04
  • Opps ! replaced . -_-
    – GKS
    Commented Nov 23, 2016 at 10:07

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.