Echo the subtitle of a PARENT page within WordPress – Part (2)

Original topic: Echo the subtitle of a PARENT page within WordPress?

I’ve discovered a separate need for the code Mark produced in relation to the original topic above. Luckily, I was able to work with another community member to achieve a similar function to handle the href for the same element this question will relate too.

Read More

I need to have the title tag populate based off the subtitle value of the parent page. However, if no parent is set, I need it to default to the default subhead of the entire site.

We were able to achieve this for the href attribute here: How to set a link based off a post_parent being set – WordPress

The current code is handled this way:

<?php
    if ($post->post_parent) {
        $permatitle = get_post_meta($post->post_parent, '_base_page_subtitle', true);
    } else {
        $permatitle = get_post_meta($post->ID, '_base_page_subtitle', true);
    }
?>

<a href="<?php echo $permalink; ?>" title="<?php echo $permatitle; ?>">

However, I need it to work on child pages as well. Any help would be appreciated and I’ll upvote anyone that can contribute to solving this.

Related posts

Leave a Reply

1 comment

  1. if you are trying to achieve the same thing (refer here) but this time for the title,

    you can do this:

    <?php
    if ($post->post_parent!=0) {
        // for child pages
        $permatitle = get_post_meta(end( get_ancestors( get_the_ID(), 'page' )), '_base_page_subtitle', true); 
    } elseif($post->ID==0||count(get_pages('child_of='.$post->ID))==0) { 
        //for HP or pages with no child
        $permatitle = get_post_meta(get_option( 'page_on_front' ), '_base_page_subtitle', true); 
    } else { 
        // for top level pages/parents
        $permatitle = get_post_meta($post->ID, '_base_page_subtitle', true); 
    } 
    

    or better yet, combine the two:

    <?php 
    if ($post->post_parent!=0) {
        // Handling of Child Pages
        $permalink = get_permalink( end( get_ancestors( get_the_ID(), 'page' )));
        $permatitle = get_post_meta(end( get_ancestors( get_the_ID(), 'page' )), '_base_page_subtitle', true); 
    } elseif($post->ID==0||count(get_pages('child_of='.$post->ID))==0) {
        // Homepage or Pages with no Parent
        $permatitle = get_post_meta(get_option( 'page_on_front' ), '_base_page_subtitle', true);
        $permalink = home_url();
    } else { 
        // Handling of Top Level/Parent Pages
        $permatitle = get_post_meta($post->ID, '_base_page_subtitle', true);
        $permalink = get_permalink( end( get_ancestors( get_the_ID(), 'page' )));
    }
    

    then you can do this after:

    <a href="<?php echo $permalink; ?>" title="<?php echo $permatitle; ?>">