How can I get an tag to wrap each ancestor that gets outputted in this condition?

I found this snippet in a different thread and it mostly does what I need, but I’m having trouble wrapping the individual pages this outputs with tags. All I can seem to add is a line break. I don’t have a lot of experience with php so unfortunately I wasn’t able to customize it to my needs. In the end I just need the firsts and second level page titles to be displayed and they need to be wrapped in individual h2’s. Thanks in advance.

    //This is the loop that pulls banner titles
function print_page_parents($reverse = true){
    global $post;

    //create array of pages (i.e. current, parent, grandparent)
    $page = array($post->ID);
    $page_ancestors = get_ancestors($post->ID, 'page');
    $pages = array_merge($page, $page_ancestors);

    if($reverse) {
        //reverse array (i.e. grandparent, parent, current)
        $pages = array_reverse($pages);
    }

    for($i=0; $i<count($pages); $i++) {
        $ban_titles.= get_the_title($pages[$i]);
        if($i != count($pages) - 1){
            $ban_titles.= " <br /> ";
        }
    }

    echo $ban_titles;
}

1 Answer
1

To wrap your titles in h2 just change echo $ban_titles; to echo '<h2>'. $ban_titles . '</h2>';.

If you want to limit number of titles displayed to 2 change for($i=0; $i<count($pages); $i++) to for($i=0; $i<2; $i++).

Hope it helps, PHP is not so scary after all 🙂

[edit]

How about that?

    //This is the loop that pulls banner titles
function print_page_parents($reverse = true){
    global $post;

    //create array of pages (i.e. current, parent, grandparent)
    $page = array($post->ID);
    $page_ancestors = get_ancestors($post->ID, 'page');
    $pages = array_merge($page, $page_ancestors);

    if($reverse) {
        //reverse array (i.e. grandparent, parent, current)
        $pages = array_reverse($pages);
    }

    $i = 0;
    if(count($pages)==1) {

    echo '<h2>'. get_the_title($pages[$i]) .'</h2>';

    } else {

    echo '<h2>'. get_the_title($pages[$i]) .'</h2>';
    echo '<h2>'. get_the_title($pages[$i+1]) .'</h2>';

    }

 }

Leave a Comment