Check whether the child page has siblings

Is there a way to check whether the child page has sibling pages. That is, whether they belong to the same parent page. If so, display the list of siblings pages within each child page.

Example:

Science books
  Book 1 
  Book 2
  Book 3

When I’m inside of:

Book 1

I want to display in list form:

Book 2
Book 3

Is it possible?

1 Answer
1

Of course it is possible. Just take a look at docs for wp_list_pages

So something like this will do the trick:

<?php
    global $post; // assuming there is global $post already set in your context
    wp_list_pages( array(
        'exclude' => $post->ID,  // exclude current post
        'parent' => $post->post_parent  // get only children of parent of current post
    ) );
?>

And if you want to use some custom HTML, then something like this should help:

<?php
    global $post; // assuming there is global $post already set in your context
    if ( $post->post_parent ) :  // if it's a child
        $siblings = new WP_Query( array(
            'post_type' => 'page',
            'post_parent' => $post->post_parent,
            'post__not_in' => array( $post->ID )
        ) );
        if ( $siblings->have_posts() ) :
?>
    <ul>
        <?php while ( $siblings->have_posts() ) : $siblings->the_post(); ?>
        <li><a href="https://wordpress.stackexchange.com/questions/304136/<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endwhile; wp_reset_postdata(); ?>
    </ul>
<?php 
        endif;
    endif;
?>

Leave a Comment