List the 5 most recent child pages

I created a hierarchical custom post type for a gallery. The parent pages are the galleries and the child pages are the albums. I want to display the most recent albums on my sidebar (so basically the most recent child pages).

'post_parent' => 0

I only find this in the codex, but this is the opposite i want, this will only list the parent pages. Here is my code so far:

$albums = new WP_Query(array(
    'post_type' => 'gallery',
    'posts_per_page' => 6
));

Related posts

Leave a Reply

1 comment

  1. Assuming you know (or know how to get) the $id (as an integer) of the parent post, use the post_parent parameter:

    $albums = new WP_Query(array(
        'post_type' => 'gallery',
        'posts_per_page' => 6,
        'post_parent' => $id
    ));
    

    Edit

    Based on this comment:

    I don’t know the parent post. I want to list the most recent child pages from ANY parent page.

    While it is easy to query only parent pages (by passing 'post_parent' => 0), it is not quite so simple to query only child pages.

    One method would be to query all gallery posts, loop through them, and add any that have a post_parent into another variable; then output that variable.

    // Query all gallery posts
    $all_albums = new WP_Query( array(
        'post_type' => 'gallery',
        'posts_per_page' => -1
    ) );
    
    // Array to hold latest albums
    $latest_child_albums = array();
    // Latest album counter
    $latest_albums_count = 0;
    // If we already have 5, no need to keep looping
    while ( 5 < $latest_albums_count ) {
        // Loop through each gallery post
        foreach ( $all_albums as $album ) {
            // If the current post has a parent
            if ( $album->post_parent != 0 ) {
                // Add it to the latest albums array
                $latest_child_albums[] = $album;
                // Increment the counter
                $latest_albums_count++;
            }
        }
    }
    
    // Loop through the array of latest albums
    if ( $latest_child_albums->have_posts() ) : while ( $latest_child_albums->have_posts() ) : $latest_child_albums->the_post();
        // Loop content here
    endwhile; endif;
    // Be kind; rewind.
    wp_reset_postdata();