代码步骤:

1,文章类型为collection的文章中获取最新一片文章(里面有用gutenburg编辑器添加的相册)。
2,从文章中获取第一个相册的图片,并将图片的id输出。
3,判断图片的数量。如果超过12张,那么最多随机显示12张不同的图片。如果不超过12张,那么全部输出。
4,结构化,用a标签套住img标签。img显示的为中等大小的图片。a链接的是全尺寸图片。

<?php
$collection_args = array(
    'post_type' => 'collection',
    'posts_per_page' => 1,
);
$collection_query = new WP_Query($collection_args);

if ($collection_query->have_posts()) {
    while ($collection_query->have_posts()) {
        $collection_query->the_post();
        if (has_block('gallery', $post->post_content)) {
            $post_blocks = parse_blocks($post->post_content);
            $img_ids = ($post_blocks['0']['attrs']['ids']);
            if (count($img_ids) > 12) {
                $nums = 12;
            } else {
                $nums = count($img_ids);
            }
            $arr = $arr_history = $img_ids;
            $selected_home_gallery_items = array();
            for ($i = 0; $i < $nums; $i++) {
                if (empty($arr_history)) {
                    $arr_history = $arr;
                }
                $key = array_rand($arr_history, 1);
                $selected = $arr_history[$key];
                unset($arr_history[$key]);
                array_push($selected_home_gallery_items, $selected . PHP_EOL);
            }
            foreach ($selected_home_gallery_items as $selected_home_gallery_item) {
                ?>
<div class="slide hasbg">
    <a href="<?php echo wp_get_attachment_image_src($selected_home_gallery_item, 'full')[0]; ?>">
        <?php echo wp_get_attachment_image($selected_home_gallery_item, 'medium'); ?>
    </a>
</div>
<?php
}
        }
    }
}?>