Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

<?php
$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:

<?php

$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.
share|improve this question

1 Answer 1

You're going about this the right way ...

  1. 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

  2. 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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.