PHP DevelopmentWordpress Development

Get Pages Parent, Child Relationship with PHP

There is WordPress function called wp_get_post_parent_id(); which takes page id as an argument. To get parent ID of any post/page,
Arrow pointing to parent-child relationship

In WordPress, pages can be organized hierarchically using parent-child relationships. This feature allows you to create a structured navigation system and group related content together. A parent page can have one or more child pages nested beneath it, forming a hierarchical structure. When a parent page is assigned, its child pages inherit its hierarchical relationship, helping to organize content logically and improve website navigation.

As on previous post about “Creating Single Post & Page Template in WordPress” we have seen about creating single page/post template with custom downloaded HTML template. We can use page parent/child relationship feature of WordPress to further modify our single page content depending on while the page has parent or not.

There is WordPress function called wp_get_post_parent_id(); which takes page id as an argument. To get parent ID of any post/page, we have to pass ID of current page or post being viewed as wp_get_post_parent_id(get_the_ID());

Using if statement, we can check for parent, child relationship to display content on the website.

For example, to put “Back to Parent Page” with link in all child pages, we have to get the title & permalink of the parent page.

<?php
$theparent = wp_get_post_parent_id(get_the_ID());
if ($theparent) { ?>
<p><a href="<?php echo get_permalink($theparent); ?>">Back to <?php echo get_the_title($theparent); ?></a></p>
<?php } ?>

—- Thankyou for Reading —-

Shares:

Related Posts

Top Categories

PHP Development
22
WordPress Theme Development
21
Wordpress Development
18
WordPress JS Development
13
Show Comments (0)
Leave a Reply

Your email address will not be published. Required fields are marked *