0

I’m trying to display the first three attachment images in each post of a custom post type separately. I believe what I am looking for is a way to put the custom post type attachments into an indexed array so that I can then chose a few individual attachments from that array and display them in their own individual divs. So far the code is not functioning efficiently and does not display all the attachments in the posts. The code I’ve supplied is just a start to be expanded upon it has got me part way there, but I'm not sure how to proceed as my php knowledge is limited.

$attachments = get_children( array(
    'post_parent'    => get_the_ID(),
    'post_type'      => 'attachment',
    'numberposts'    => -1,
    'post_status'    => 'inherit',
    'post_mime_type' => 'image',
    'order'          => 'ASC',
    'orderby'        => 'menu_order ASC'
) );
foreach ( $attachments as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'medium');
}

1 Answer 1

0

Managed to find a solution that display the array correctly:

$attachments = get_children( array(
    'post_parent'    => get_the_ID(),
    'post_type'      => 'attachment',
    'numberposts'    => -1,
    'post_status'    => 'inherit',
    'post_mime_type' => 'image',
    'order'          => 'ASC',
    'orderby'        => 'menu_order ASC'
    ) );

    $imgArray = array();
    $counter = 0;
    foreach ( $attachments as $attachment_id => $attachment ) {

    $imgArray[$counter] = $attachment_id;
    $counter++;
    if($counter > 2) {
    break;
    }
    } 
?>
<div class="attachment1"><?php echo wp_get_attachment_image( $imgArray[0], 'medium'); ?></div>
<div class="attachment2"><?php echo wp_get_attachment_image( $imgArray[1], 'medium'); ?></div>
<div class="attachment3"><?php echo wp_get_attachment_image( $imgArray[2], 'medium'); ?></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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