I want to pull four random images from the current post's attachments to display as "featured images". Therefor I am using the following function:
function fs_gallery_featured_thumbs( $post_id ) {
// DEBUG: validate parent post ID
echo $post_id;
// Query to get images for this post
$query = array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'RAND',
'exclude' => get_post_thumbnail_id( $post_id ) );
$images = array_rand( get_children( $query ), 4);
// If images exist for this page
if ( $images ) {
echo '<div class="featured-thumbs">';
$i = 1;
foreach ( $images as $image ) {
$imageAttributes = wp_get_attachment_image_src( $image, 'gallery-thumbnail-1x1' );
echo '<a href="'.get_permalink().'" class="featured-thumb-link featured-thumb-link-'.$i.'"><img src="'.$imageAttributes[0].'" alt="'.the_title_attribute(array('echo'=>0)).'" class="featured-thumb featured-thumb-'.$i++.'" width="152px" height="152px" /></a>';
}
echo '</div>';
}
}
The only parameter is passed from inside the loop via the_ID()
and is in fact returning the correct parent post ID (I verified this using echo $post_id;
inside above function.
However, for some reason, the array images
contains four random items of ALL images that are inside the media gallery, not only the ones which are attached to the current post.
How can I really only get the images which are attached to the post? When I use the [gallery]
shortcode in this post, the correct images are shown. All I want is four random images from that gallery.
Any ideas?
Not sure if this has anything to do with it: the posts which all the other (wrong) images were attached to, were deleted at some point. The images still linger inside the media gallery however, however the post ID of the post they are "used in" (not sure about the correct English term here, my WP is German) is different to my post_parent
.
Thx.
$post_id
, but calling$post->ID
in your args array?post_parent
is still correct, but ALL images appear (well 4 of them).post_parent
? And 2) pass0
topost_parent
?88
(which is the correct post ID) to the function and it worked; I then passed$post->ID
rather thanthe_ID()
and it also seems to work. It seems that it was only a stupid mistake. If you write an answer I will happily accept it. Cheers.the_ID()
? It doesn't appear in your code, that I can see.