Finding all parent pages in WodPress [Code Snippet]

Sometimes we needs to find all parent pages of current page in WordPress. It is useful to create a breadcrumb. Here is a example code snippet to find all parent pages.

<ul class="page-breadcrumbs">
    <li><a href="<?php echo home_url(); ?>"><?php _e( 'Home', 'mondira' ) ?></a></li>
    <?php
    global $post;
    $parent_id = $post->post_parent;
    $breadcrumbs = array();
    while ( $parent_id ) {
        $page = get_page( $parent_id );
        $breadcrumbs[] = '<li><a href="' . get_permalink( $page->ID ) . '">' . get_the_title( $page->ID ) . '</a></li>';
        $parent_id = $page->post_parent;
    }
    $breadcrumbs = array_reverse( $breadcrumbs );
    foreach ( $breadcrumbs as $crumb ) echo $crumb;
    ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title();?></a></li>
</ul>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: