You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PHP短代码实现指定文件夹视频的循环随机播放

实现随机循环播放指定文件夹视频的短代码方案

以下是符合需求的WordPress短代码实现,支持通过[shuffle_play_gallery folder="naturevideos"]调用,实现指定文件夹内视频的随机循环播放:

function shuffle_play_gallery_shortcode($atts) {
    // 提取短码参数,默认文件夹为空
    $atts = shortcode_atts(array(
        'folder' => '',
    ), $atts);

    // 清理文件夹名称,防止路径遍历攻击
    $folder = sanitize_text_field($atts['folder']);
    if (empty($folder)) {
        return '<p>请指定视频文件夹名称。</p>';
    }

    // 定义视频文件的基础目录和URL(请根据实际路径修改)
    $base_dir = WP_CONTENT_DIR . '/videos/' . $folder . '/';
    $base_url = content_url('/videos/' . $folder . '/');

    // 检查文件夹是否存在
    if (!is_dir($base_dir)) {
        return '<p>指定的视频文件夹不存在。</p>';
    }

    // 获取文件夹内所有MP4格式的视频文件
    $video_files = glob($base_dir . '*.mp4');
    if (empty($video_files)) {
        return '<p>该文件夹中没有MP4视频文件。</p>';
    }

    // 随机打乱视频文件顺序
    shuffle($video_files);

    // 转换为可访问的URL列表
    $video_urls = array();
    foreach ($video_files as $file) {
        $video_urls[] = $base_url . basename($file);
    }

    // 生成HTML和JavaScript代码
    $output = '<div class="shuffle-video-gallery">';
    $output .= '<video width="320" height="240" controls id="shuffle-video-player">';
    $output .= '<source src="' . esc_url($video_urls[0]) . '" type="video/mp4">';
    $output .= '您的浏览器不支持视频播放标签。';
    $output .= '</video>';
    $output .= '<script>';
    $output .= 'const videoUrls = ' . json_encode($video_urls) . ';';
    $output .= 'const videoPlayer = document.getElementById("shuffle-video-player");';
    $output .= 'function playRandomVideo() {';
    $output .= '  const randomIndex = Math.floor(Math.random() * videoUrls.length);';
    $output .= '  videoPlayer.src = videoUrls[randomIndex];';
    $output .= '  videoPlayer.play();';
    $output .= '}';
    $output .= 'videoPlayer.addEventListener("ended", playRandomVideo);';
    $output .= '</script>';
    $output .= '</div>';

    return $output;
}

// 注册短码
add_shortcode('shuffle_play_gallery', 'shuffle_play_gallery_shortcode');

关键说明:

  1. 路径配置:请根据实际视频存储路径修改$base_dir和$base_url,示例中默认视频存储在wp-content/videos/目录下的子文件夹中。
  2. 安全处理:通过sanitize_text_field清理文件夹名称,避免路径遍历攻击;使用esc_url确保视频URL的安全性。
  3. 随机播放逻辑:页面加载时先随机打乱视频列表,当当前视频播放结束后,自动从列表中随机选择下一个视频播放,实现无限随机循环。
  4. 兼容性:保留了原代码中的浏览器不支持提示,确保基础兼容性。

使用方法:

将上述代码添加到主题的functions.php文件或自定义插件中,即可通过短码[shuffle_play_gallery folder="你的文件夹名称"]在页面或文章中调用。

内容的提问来源于stack exchange,提问作者Sawper hayabosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:35:10