0

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?

1 Answer 1

2

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;
4
  • can i use it on functions.php?
    – Shawn
    Jun 11, 2021 at 4:49
  • i need media id not the full url
    – Shawn
    Jun 11, 2021 at 5:59
  • 1
    "for testing purposes") This is an id - $image[0]->ID.
    – anton
    Jun 11, 2021 at 6:11
  • thanks @anton it works
    – Shawn
    Jun 11, 2021 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.