wp query - Get last child of given page by ID

admin2025-06-06  1

I've got the following code- I'm trying to get the last child page of a page with ID 4117. Here's my code thus far:

// WP_Query arguments
$args = array(
    'post_parent'            => '4117',
    'posts_per_page'         => '1',
    'order'                  => 'DESC',
    'orderby'                => 'menu_order',
);

// The Query
$query = new WP_Query( $args );

$posts = $query->posts;

foreach($posts as $post) {

    echo $post->post_title;

}

But it doesn't appear to do anything. Any clues as to what my issue may be?

I've got the following code- I'm trying to get the last child page of a page with ID 4117. Here's my code thus far:

// WP_Query arguments
$args = array(
    'post_parent'            => '4117',
    'posts_per_page'         => '1',
    'order'                  => 'DESC',
    'orderby'                => 'menu_order',
);

// The Query
$query = new WP_Query( $args );

$posts = $query->posts;

foreach($posts as $post) {

    echo $post->post_title;

}

But it doesn't appear to do anything. Any clues as to what my issue may be?

Share Improve this question asked Nov 6, 2018 at 21:23 warm__tapewarm__tape 611 silver badge11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

WP_Query defaults to getting posts, not pages.

From the above reference page:

Display content based on post and page parameters. Remember that default post_type is only set to display posts but not pages.

This code:

// WP_Query arguments
$args = array(
    'post_parent'            => '4117',
    'post_type'              => 'page',
    'posts_per_page'         => '1',
    'order'                  => 'DESC',
    'orderby'                => 'menu_order',
);

// The Query
$query = new WP_Query( $args );
$posts = $query->posts;
foreach ( $posts as $post ) {
    echo $post->post_title;
}

...should do what you want.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749201658a317215.html

最新回复(0)