如何在 Wordpress 中获取 4 张随机图像并用作 4 个相关帖子的缩略图?



我想在我的页面上的相关帖子缩略图中显示4个不同的图像,这些图像是从URL中的图像中随机选择的。但是,每个相关帖子的缩略图图像都是相同的。

我不知道如何在每个相关帖子中添加不同的随机图像到这个代码中。

我的PHP代码:

<?php
/**
related posts
*/
$tags = wp_get_post_tags($post->ID);
$images = array(
'https://img-blog.com/20200916142100590.jpg',
'https://img-blog.com/20200915155348194.jpg',
'https://img-blog.com/20200910152002780.jpg',
);
$image_url = $images[array_rand( $images, 1 )];
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;

$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'showposts'=>4,  // Number of related posts that will be shown.
'caller_get_posts'=>1
);

$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<div id="relatedposts"><h3>Related posts</h3><ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>

<?php
if ( has_post_thumbnail() ) { ?>
<li><div class="relatedthumb"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail(); ?><?php the_title(); ?></a></div></li>
<?php } else { ?>
<li><div class="relatedthumb"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><img src="<?php echo $image_url ?>" width="196" height="110" alt="<?php the_title_attribute(); ?>" /><?php the_title(); ?></a></div></li>
<?php }
?>

<?php
}
echo '</ul>';
}
}
$post = $backup;
wp_reset_query();
/**
end
*/
?>

我的相关帖子的缩略图

请在循环内使用以下行,而不要在循环外使用。所以它每次都会随机化链接。

while ($my_query->have_posts()) {

$image_url=$images[array_rand($images,1(]

最新更新