I needed to pass an image to a Pinterest plugin in posts without a featured imageFeatured 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.phploop-single.php
where the sharing buttons are located.
After a lot of reading and trial and error I got this code to work.
<?php 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: why do I need to use a foreachforeach
to get the attachment_idattachment_id
? Specifically
Specifically, what is this line doing?
I have looked at this quite a bit and I can't tell if my knowledge is lacking in wordpress or php or both. 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 foreachforeach
could I get the image id out.
Is there an easier way to get the attachment_idattachment_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. Sorry if this a rookie question, I don't want to waste anyones time.
PS - the Pinterest code (or rather AddThis code) that uses the attachment_id is here
<a class="addthis_button_pinterest_pinit" pi:pinit:url="<?php the_permalink(); ?>" pi:pinit:description="<?php the_title(); ?>" pi:pinit:media="<?php echo $thumb_for_pinterest[0]; ?>" pi:pinit:layout="horizontal"></a>