如何从媒体集中随机获取媒体ID

时间:2021-06-10 作者:Sabbir

我尝试使用以下方法从wordpress媒体库获取随机媒体id:

$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);
但它不会正常工作。

有没有办法获得媒体id randonly?

1 个回复
最合适的回答,由SO网友:anton 整理而成

您可以使用get_posts() 函数获取随机帖子,无需额外的php操作
只需将默认orderby属性更改为";兰德公司;并将posts属性的数量设置为;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;