How to retrieve attachments from child pages of a specific Page?

3 views
0

How would I retrieve attachments from all subpages of a specific Page ID?

Example:

SPECIFIC PAGE

  • Child (with attachments)
  • Child (with attachments)
  • Child (with attachments)

I’m currently using this code to retrieve all attachments site-wide, however I would like to limit this to only pull images from all children of a specific Page.

$args = array( 
    'post_type'   => 'attachment', 
    'numberposts' => -1, 
    'post_status' => null, 
    'post_parent' => null 
); 
$attachments = get_posts( $args );
if ( $attachments ) {
    foreach ( $attachments as $post ) {
        setup_postdata( $post );
        the_title();
        the_attachment_link( $post->ID, false );
        the_excerpt();
    }
}

Almost there using this code below:

$mypages = get_pages( 'child_of=19' );
foreach ( $mypages as $mypage  ) {
    $attachments = get_children( array(
        'post_parent'    => $mypage->ID, 
        'numberposts'    => 1, 
        'post_type'      => 'attachment', 
        'post_mime_type' => 'image', 
        'orderby'        => 'rand'
    ) );        
    if ( $attachments ) {
        foreach ( $attachments as $post ) {
            setup_postdata($post);
                the_title();
                the_attachment_link( $post->ID, false );
                the_excerpt();
        }
    }
}

However, there are two remaining issues:

  1. Limiting the amount of total photos pulled. Using 'numberposts' only limits the amount of images pulled from each post.
  2. Randomization. Orderby => rand only randomizes the images within each post. I would like to randomly shuffle the order for everything.