是的,这是可能的,而且不是那么困难。您在创建帖子时上传图像。
然后在 single.php 中使用 get_children 从帖子中获取所有图像。
假设在循环中:
$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=$post->ID' );
并像这样输出它们:
if ($images)
{
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
对于您的随机图像,您可以使用与上面相同的 get_children 但添加&numberposts=1到 args 字符串。
或类似的东西:
function fetch_random_img($postid='') {
global $wpdb;
if (empty($postid))
{
//we are going for random post and random image
$postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY RAND() LIMIT 1");
}
$imageid = $wpdb->get_var($wpdb->prepare("SELECT ID FROM wp_posts WHERE post_type='attachment' AND post_mime_type LIKE 'image/%' AND post_parent=$postid ORDER BY RAND() LIMIT 1"));
if ($imageid) {
echo wp_get_attachment_image( $imageid, 'full' );
}
else {
return false;
}
}
这只会给你一个随机图像,而且它是随机的,而 get_children 每次都会拉出相同的图像,除非你添加 order 和 orderby 参数,这将允许你更改输出的图像。
要在 div 中回显图像,只需调用函数:
<div>
<?php fetch_random_img(); ?>
</div>