Question

So I have two code snippets, trying to get the child pages of the current page. The current page is "Sample", and the following code lives in page-sample.php.

The first snippet uses get_posts()

$args = array(
                'post_parent' => $post->ID,
                'post_type'   => 'page', 
                'post_status' => 'any' 
            );
$children = get_posts( $args );
// $children = get_children( $args ); //this also works,btw

foreach($children as $child){
    setup_postdata( $child );
    echo "<h1>" .  $child->post_title . "</h1>";
}

This correctly displays the child posts.

The second snippet uses a new WP_Query object

$args = array(
                'post_parent' => $post->ID,
                'post_type'   => 'page', 
                // 'numberposts' => -1,
                'post_status' => 'any' 
            );
$child_pages_query= new WP_Query(args);
// echo $child_pages_query->post_count; // wrong answer already!
if ($child_pages_query->have_posts()){
    while($child_pages_query->have_posts()){
        $child_pages_query->the_post();
        echo "<h1> " . $post->post_title . " </h1>";
        }
}

This incorrectly displays all posts . No pages, just posts.

I really can't figure out what I'm doing wrong

  1. No plugins are installed
  2. I commented out all parent theme code, including header,footer, till it was a bare html page, even though I couldn't see anything in header.php or footer.php that could be affecting this.

Now the funny part is changing the WP_Query args doesn't seem to be making any difference. Always, all posts. WP_Query works on other pages.

Any help would be appreciated. Much thanks in advance!

Était-ce utile?

La solution

You are missing a $ before args in

$child_pages_query= new WP_Query(args); 

It should be

$child_pages_query= new WP_Query($args);

Autres conseils

You forgot the $ on your WP_Query args array:

$child_pages_query= new WP_Query(args);

Should be:

$child_pages_query= new WP_Query($args);

This should show up as a PHP warnings/notice in the error logs, and is preventable with standard debugging and development practices.

In your WP_Query code instead of

echo $post->post_title;     

Try

echo $child_pages_query->post->post_title;
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top