I know how to add an image and a gallery. I need to have one image from the galley show on the page at random each time the page is loaded.
The page should only show one image at a time.
Is there a plugin or short code to do this? I know how to make gallery’s random, but they show all the images.
Answer:
$args = array(
'post_type' => 'attachment',
'numberposts' => 1,
'orderby' => 'rand',
'post_status' => null,
'post_parent' => get_the_ID(),
'post_mime_type' => 'image'
);
have_posts(); //must be in the loop
the_post(); //set the ID
$images = get_children( $args );
if ($images) {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
wp_reset_query();
You should use the
'orderby' => 'rand'
parameter for theget_children()
attachments function.For instance:
You can also pull the IDs from ALL galleries on a page using
get_post_galleries()
and you don’t need an extra loop.Reference
list()
shuffle()
get_post_galleries()
wp_list_pluck()
explode()
implode()
array_unique()
get_the_ID()
wp_get_attachment_image()
This code answers the question. In a page or post containing a gallery, it will take one random image from the gallery and display only that image. It goes inside the wordpress loop ( code here actually includes the loop ).