admin管理员组

文章数量:1290956

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?

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?

Share Improve this question edited Jun 11, 2021 at 6:47 Shawn asked Jun 10, 2021 at 20:22 ShawnShawn 11710 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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;

本文标签: attachmentshow to get random media id from media gallery