How to retrieve a list of sibling pages on a WordPress page

To retrieve a list of a WordPress page’s sibling pages, you can use the get_pages() function with the appropriate arguments. You’ll need the current page’s parent ID to fetch its sibling pages.

Here’s a code snippet to display a list of the current page’s sibling pages:

global $post;

// Get the current page's parent ID
$parent_id = $post->post_parent;

// Get the sibling pages
$sibling_pages = get_pages(array(
'child_of' => $parent_id,
'sort_column' => 'menu_order', // You can change the sorting order (e.g., 'post_date', 'post_title', etc.)
'sort_order' => 'ASC', // Change to 'DESC' for descending order
'exclude' => $post->ID // Exclude the current page from the list
));

// Display the sibling pages
if (!empty($sibling_pages)) {
echo '<ul class="sibling-pages-list">';
foreach ($sibling_pages as $sibling_page) {
echo '<li><a href="' . get_permalink($sibling_page->ID) . '">' . $sibling_page->post_title . '</a></li>';
}
echo '</ul>';
} else {
echo 'No sibling pages found.';
}

You can add this code snippet to your WordPress theme’s page.php template or any other template file where you want to display the list of sibling pages. This code will generate an unordered list (ul) of the sibling pages with links to each sibling page.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

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