How can PHP be used to dynamically generate and display the current page hierarchy on a website?

To dynamically generate and display the current page hierarchy on a website, you can use PHP to retrieve the parent pages of the current page and display them in a hierarchical structure. This can be achieved by querying the parent page IDs of the current page and then recursively fetching and displaying their parent pages until reaching the root page.

<?php
// Get the current page ID
$current_page_id = get_the_ID();

// Function to recursively display parent pages
function display_parent_pages($page_id) {
    $parent_id = wp_get_post_parent_id($page_id);
    
    if ($parent_id) {
        display_parent_pages($parent_id);
        echo '<li>' . get_the_title($parent_id) . '</li>';
    }
}

// Display the current page hierarchy
echo '<ul>';
echo '<li>' . get_the_title($current_page_id) . '</li>';
display_parent_pages($current_page_id);
echo '</ul>';
?>