How to query posts from multiple parents

I want to query the current page siblings AND children.

Using 'post_parent' => $post->post_parent OR 'post_parent' => $post->ID separately I get it to work.

Read More

But I want to query them simultaneously.

I tried to “merge” them using variables but it seems like it doesn’t work. The output I get is all the pages on the site (same as post_parent is 0).

Full code:

<?php
$mysibling        = $post->post_parent;
$mychild          = $post->ID;
$mychildmysibling = array( $mychild, $mysibling );

$args = array(
    'post_type'       => 'page',
    'posts_per_page'  => -1,
    'post_parent'     => $mychildmysibling,  
    'sort_order'      => 'asc'
 );

$parent = new WP_Query( $args );

if ( $parent->have_posts() ) : ?>

<ul>
    <?php while ( $parent->have_posts() ) : $parent->the_post(); ?>
        <li><a href="<?php the_permalink() ?>"><?php the_title() ?></a></li>
    <?php endwhile ?>
</ul>

<?php endif; wp_reset_query(); ?>

Related posts

Leave a Reply

1 comment

  1. Your query should look like this:

    $args = array(
      'post_type'       => 'page',
      'posts_per_page'  => -1,
      'post_parent__in' => $mychildmysibling,  
      'sort_order'      => 'asc'
    );
    

    As written on this page: https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters

    post_parent (int) – use page id to return only child pages. Set to 0
    to return only top-level entries.
    post_parent__in (array) – use post
    ids. Specify posts whose parent is in an array. (available since
    Version 3.6)

    Think about it as a MySQL question where you use the “IN” clause when working with multiple values.