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 badges1 Answer
Reset to default 2You 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
版权声明:本文标题:attachments - how to get random media id from media gallery 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741509971a2382549.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论