I needed to pass an image to a Pinterest plugin in posts without a Featured Image so I wrote a little function to get the id of the first picture in a post. This code is in the loop-single.php
where the sharing buttons are located.
if ( has_post_thumbnail()) {
$thumb_for_pinterest = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
} else {
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'numberposts' => 1, // show all -1
'post_status' => 'inherit',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ASC'
) );
foreach ( $attachments as $attachment_id => $attachment ) {
$thumb_for_pinterest = wp_get_attachment_image_src($attachment_id, 'full' );
}
}
My question is this: why do I need to use a foreach
to get the attachment_id
?
Specifically, what is this line doing?
foreach ( $attachments as $attachment_id => $attachment ) {...
I believe an associative array is being returned with only 1 object in it. However, when I tried to just pop the object out of the array and use it I got lots of errors. Only by putting it in the foreach
could I get the image id out.
Is there an easier way to get the attachment_id
of the first image in a post?
I have read a lot of questions and googled this quite extensively, but couldn't understand it completely.