$post->post_parent behaves different on page then in functions.php

I created/modified a function to display breadcrumbs on pages on WordPress. The modified version makes use of #post->post_parent to get the parent of a page in order to have a full breadcrumb trail (home > page 1 > page 2 > page 3 vs. home > page 3)

The code executes perfectly on page (ie. home > page 1 > page 2 > page 3). But when I place it into a function and call it form the functions.php page it cannot detect if the page has a parent using $post->post_parent (ie. page 3 vs. home > page 3).

Read More

Could this be because the on page code is executed in the_loop but the function is somehow outside of it?

On page code:

if (!is_home()) {
            echo "<ul id='breadcrumb'>";
            echo '<li><a href="';
            echo get_option('home');
            echo '">HOME';
            echo "</a></li>";
            if (is_category() || is_single()) {
                the_category('title_li=');
                if (is_single()) {
                    the_title('<li>', '</li>');
                    echo "</ul>";
                }
            } elseif (is_page()) {
                if(!$post->post_parent){
                    //echo "No Parent";
                    }
                else{

                    echo '<li>'.  wp_list_pages('include='.$post->post_parent.'&title_li=' ).'</li>';
                }


                the_title('<li>', '</li>');
                echo "</ul>";
            }
        }

Function code:

function the_breadcrumb() {
        if (!is_home()) {
            echo "<ul id='breadcrumb'>";
            echo '<li><a href="';
            echo get_option('home');
            echo '">HOME';
            echo "</a></li>";
            if (is_category() || is_single()) {
                the_category('title_li=');
                if (is_single()) {
                    the_title('<li>', '</li>');
                    echo "</ul>";
                }
            } elseif (is_page()) {
                if(!$post->post_parent){
                    //echo "No Parent";
                    }
                else{

                    echo '<li>'.  wp_list_pages('include='.$post->post_parent.'&title_li=' ).'</li>';
                }


                the_title('<li>', '</li>');
                echo "</ul>";
            }
        }
    }

There is nothing inherently different about this code except that it is now wrapped in a function. The fact that it doesn’t display the parent pages is frustrating. I don’t want to have to include this code on every page template I create.

Help & Suggestions will be greatly appreciated!

Related posts

Leave a Reply

2 comments