I tried to get random media id from wordpress media gallery using this:
$image_ids = get_posts(
array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'posts_per_page' => -1
)
);
// based on the number of image_ids retrieved, generate a random number within bounds.
$num_of_images = count($image_ids);
$random_index = rand(0, $num_of_images);
$random_image_id = $image_ids[$random_index];
// now that we have a random_image_id, lets fetch the image itself.
$media_id = get_post($random_image_id);
But it won’t work properly.
Is there any way to get media id randonly?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use get_posts() function to get random post, without additional php manipulation.
Just change default orderby attribute to “rand” and set number of posts attribute equals to “1”.
$image = get_posts(
array(
'orderby' => 'rand', //random order
'numberposts' => 1, // numberposts, not posts_per_page
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit'
)
);
//for testing purposes
echo $image[0]->ID;
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0