wordpress随机获取文章内的gallery和video

假设文章ID=5

随机输出相册内20张图片:

<?php 
        $post=5;
        $ids = [];
        $array_key_names=[];
        if (has_block('gallery', $post)) {
            $post_blocks = parse_blocks(get_the_content($post));
            $ids = $post_blocks[0]['attrs']['ids'];
        } 
        else {
            $gallery = get_post_gallery( $post->ID, false );
            $ids = explode ( ",", $gallery['ids'] );
        }
        shuffle($ids);
        $array_key_names = array_rand($ids,20);
        foreach($array_key_names as $array_key_name){
// echo ...;
}?>

随机输出1个视频

<?php
$post = 5;
$ids = [];
$videos = [];
$array_key_name = [];
if (has_block('video', $post)) {
    $post_blocks = parse_blocks(get_the_content($post));
    foreach ($post_blocks as $post_block) {
        array_push($videos, $post_block['attrs']['id']);
    }
}
$ids = array_filter($videos);
shuffle($ids);
if (!empty($ids)) {
    $array_key_name = array_rand($ids, 1);
    $video_id = $ids[$array_key_name];
?>
      <video preload="auto" loop="true" muted="true" playsinline="true">
<source src="<?php echo wp_get_attachment_url($video_id); ?>" type="video/mp4">
      </video>
<?php } ?>