get_children
will return
an associative array of posts […] with post IDs as array keys, or an empty array if no posts are found.
This statement $attachment_id => $attachment
is the same as the more commonly used $key => $value
.
Using this command echo '<pre>'.print_r($attachments,true).'</pre>';
we get the following:
resumed version of a get_children
with numberposts => 2
Array
(
[83] => stdClass Object
(
[ID] => 83
[post_author] => 1
[post_date] => 2012-06-22 05:06:22
[post_content] =>
[post_title] => barajas
[post_excerpt] =>
[post_status] => inherit
[post_name] => barajas-4
[post_modified] => 2012-06-22 05:06:22
[post_modified_gmt] => 2012-06-22 05:06:22
[post_parent] => 28
[guid] => http://wp00.dev/wp-content/uploads/barajas3.jpg
[menu_order] => 0
[post_type] => attachment
[post_mime_type] => image/jpeg
)
[180] => stdClass Object
(
[ID] => 180
[post_author] => 1
[post_date] => 2012-06-30 04:18:06
[post_content] =>
[post_title] => Yuri Atom_00281
[post_excerpt] =>
[post_status] => inherit
[post_name] => yuri-atom_00281
[post_modified] => 2012-06-30 04:18:06
[post_parent] => 28
[guid] => http://wp00.dev/wp-content/uploads/Yuri-Atom_00281.jpg
[menu_order] => 0
[post_type] => attachment
[post_mime_type] => image/jpeg
)
)
So, [83]
and [180]
are the $key and stdClass Object
is their $value.
I think when calling get_children
a foreach is almost mandatory, and this will be clear next…
If you use get_posts
with exactly the same arguments, the result will be exactly the same except for one difference, the returned array will have numeric sequential keys:
Array
(
[0] => stdClass Object
(
[ID] => 83
[post_author] => 1
[post_date] => 2012-06-22 05:06:22
)
[1] => stdClass Object
(
[ID] => 180
[post_author] => 1
[post_date] => 2012-06-30 04:18:06
)
)
All that being said, if you use get_posts
and numberposts => 1
, you can substitue the foreach
block for:
$thumb_for_pinterest = wp_get_attachment_image_src($attachments[0]->ID, 'full' );
With get_children
we don’t know what’s the $key
number, as it is the same as the Attachment ID, hence the foreach…
But with a regular numeric key (0, 1, 2, 3… etc), you can drop the foreach
and call the first element of the array directly ($attachments[0]
) and its object element (->ID
).