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:
- Limiting the amount of total photos pulled. Using
'numberposts'
only limits the amount of images pulled from each post. - Randomization.
Orderby => rand
only randomizes the images within each post. I would like to randomly shuffle the order for everything.
You’re going about this the right way …
Your query is like a loop … so to limit total images you’d need to add them all to an array first, and then how would you determine how to limit the total
eg what if one page had 50 images and the next page had 1
Along with your first point … your current code is a Loop that runs through each child page. So you would need to get all your images into an array first and you can randomise them.
Suggestion – try this WordPress Codex wp_get_attachment_image to list the images on your pages
and compare it with your codex / code sample http://codex.wordpress.org/Template_Tags/get_posts#Show_all_attachments
Damien
You can try get_pages like this way:
NOTE: child_of
Note that the child_of parameter will also fetch “grandchildren” of the given ID, not just direct descendants. Parent will limit this to just the children that have this as a parent. No grandchildren. So you could store all of the attachment data in a multidimensional array and shuffle it. Then use a for loop to display the proper number of attachments.