插件功能说明

  1. 自动为无特色图片的文章 / 页面随机分配指定目录下的图片
  2. 支持自定义随机图片目录(默认 wp-content/uploads/random-thumb/)
  3. 可设置仅对特定文章类型生效(如 post/page)
  4. 支持手动触发重新随机设置特色图片

完整插件代码

将以下代码保存为 random-featured-image.php,上传到 wp-content/plugins/ 目录,然后在后台启用插件即可。

<?php
/**
 * Plugin Name: 随机特色图片
 * Plugin URI: https://github.com/
 * Description: 为无特色图片的文章随机分配指定目录下的图片作为特色图片
 * Version: 1.0
 * Author: 自定义
 * Author URI: https://
 * License: GPL2
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// ======================== 核心功能 ========================
class Random_Featured_Image {
    public function __construct() {
        // 文章保存时自动设置随机特色图片
        add_action('save_post', array($this, 'set_random_thumbnail_on_save'), 10, 3);
        
        // 添加后台设置页面
        add_action('admin_menu', array($this, 'add_settings_page'));
        add_action('admin_init', array($this, 'register_settings'));
        
        // 添加手动刷新特色图片的批量操作
        add_filter('bulk_actions-edit-post', array($this, 'add_bulk_action'));
        add_action('admin_action_random_thumbnail', array($this, 'handle_bulk_action'));
    }

    /**
     * 获取随机图片列表
     */
    private function get_random_images() {
        // 获取设置的图片目录(默认 wp-content/uploads/random-thumb/)
        $image_dir = get_option('rfi_image_directory', WP_CONTENT_DIR . '/uploads/random-thumb/');
        $image_url = str_replace(ABSPATH, site_url('/'), $image_dir);
        
        // 创建默认目录(如果不存在)
        if (!file_exists($image_dir)) {
            wp_mkdir_p($image_dir);
        }

        // 支持的图片格式
        $allowed_ext = array('jpg', 'jpeg', 'png', 'gif', 'webp');
        $images = array();

        // 扫描目录获取图片
        if ($files = scandir($image_dir)) {
            foreach ($files as $file) {
                $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                if (in_array($ext, $allowed_ext) && is_file($image_dir . $file)) {
                    $images[] = array(
                        'path' => $image_dir . $file,
                        'url'  => $image_url . $file
                    );
                }
            }
        }

        return $images;
    }

    /**
     * 为单篇文章设置随机特色图片
     */
    public function set_random_thumbnail($post_id) {
        // 排除自动保存/修订版本
        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
            return;
        }

        // 检查文章类型是否允许
        $allowed_post_types = get_option('rfi_allowed_post_types', array('post'));
        $post_type = get_post_type($post_id);
        if (!in_array($post_type, $allowed_post_types)) {
            return;
        }

        // 如果已有特色图片,跳过(可根据需求修改)
        if (has_post_thumbnail($post_id)) {
            // 如需强制替换已有图片,注释上面的判断,取消下面注释
            // delete_post_thumbnail($post_id);
            return;
        }

        $images = $this->get_random_images();
        if (empty($images)) {
            return;
        }

        // 随机选一张图片
        $random_image = $images[array_rand($images)];
        
        // 将图片添加到媒体库并设置为特色图片
        $this->add_image_to_media_library($random_image['path'], $random_image['url'], $post_id);
    }

    /**
     * 文章保存时触发
     */
    public function set_random_thumbnail_on_save($post_id, $post, $update) {
        // 仅在启用自动设置时生效
        if (get_option('rfi_auto_set', 'yes') !== 'yes') {
            return;
        }
        $this->set_random_thumbnail($post_id);
    }

    /**
     * 将图片添加到媒体库并设置为特色图片
     */
    private function add_image_to_media_library($image_path, $image_url, $post_id) {
        // 获取图片信息
        $image_data = file_get_contents($image_path);
        $filename = basename($image_path);

        // 上传图片到媒体库
        $upload = wp_upload_bits($filename, null, $image_data);
        if (!$upload['error']) {
            $wp_filetype = wp_check_filetype($filename, null);
            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title'     => sanitize_file_name($filename),
                'post_content'   => '',
                'post_status'    => 'inherit'
            );

            // 插入附件
            $attach_id = wp_insert_attachment($attachment, $upload['file'], $post_id);
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
            wp_update_attachment_metadata($attach_id, $attach_data);

            // 设置为特色图片
            set_post_thumbnail($post_id, $attach_id);
        }
    }

    // ======================== 后台设置 ========================
    /**
     * 添加设置页面
     */
    public function add_settings_page() {
        add_options_page(
            '随机特色图片设置',
            '随机特色图片',
            'manage_options',
            'random-featured-image',
            array($this, 'render_settings_page')
        );
    }

    /**
     * 注册设置项
     */
    public function register_settings() {
        register_setting('rfi_settings_group', 'rfi_auto_set');
        register_setting('rfi_settings_group', 'rfi_image_directory');
        register_setting('rfi_settings_group', 'rfi_allowed_post_types');

        add_settings_section(
            'rfi_main_section',
            '基本设置',
            array($this, 'render_settings_section'),
            'random-featured-image'
        );

        add_settings_field(
            'rfi_auto_set',
            '自动设置特色图片',
            array($this, 'render_auto_set_field'),
            'random-featured-image',
            'rfi_main_section'
        );

        add_settings_field(
            'rfi_image_directory',
            '图片目录',
            array($this, 'render_image_dir_field'),
            'random-featured-image',
            'rfi_main_section'
        );

        add_settings_field(
            'rfi_allowed_post_types',
            '生效的文章类型',
            array($this, 'render_post_types_field'),
            'random-featured-image',
            'rfi_main_section'
        );
    }

    /**
     * 渲染设置页面
     */
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1>随机特色图片设置</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('rfi_settings_group');
                do_settings_sections('random-featured-image');
                submit_button();
                ?>
            </form>
            <div style="margin-top:20px;padding:10px;background:#f1f1f1;">
                <h3>使用说明</h3>
                <ul>
                    <li>1. 请将随机图片上传到设置的目录中(默认:wp-content/uploads/random-thumb/)</li>
                    <li>2. 支持批量操作:在文章列表中选择文章,批量操作选择「随机设置特色图片」即可</li>
                    <li>3. 支持的图片格式:jpg、jpeg、png、gif、webp</li>
                </ul>
            </div>
        </div>
        <?php
    }

    /**
     * 渲染设置说明
     */
    public function render_settings_section() {
        echo '<p>配置随机特色图片的相关参数</p>';
    }

    /**
     * 自动设置开关
     */
    public function render_auto_set_field() {
        $value = get_option('rfi_auto_set', 'yes');
        ?>
        <select name="rfi_auto_set">
            <option value="yes" <?php selected($value, 'yes'); ?>>是(保存文章时自动设置)</option>
            <option value="no" <?php selected($value, 'no'); ?>>否(仅手动批量设置)</option>
        </select>
        <?php
    }

    /**
     * 图片目录设置
     */
    public function render_image_dir_field() {
        $value = get_option('rfi_image_directory', WP_CONTENT_DIR . '/uploads/random-thumb/');
        ?>
        <input type="text" name="rfi_image_directory" value="<?php echo esc_attr($value); ?>" style="width: 500px;">
        <p class="description">请填写图片目录的绝对路径,默认:<?php echo WP_CONTENT_DIR; ?>/uploads/random-thumb/</p>
        <?php
    }

    /**
     * 文章类型设置
     */
    public function render_post_types_field() {
        $selected = get_option('rfi_allowed_post_types', array('post'));
        $post_types = get_post_types(array('public' => true), 'objects');
        ?>
        <div>
            <?php foreach ($post_types as $pt) : ?>
                <label style="display: block; margin: 5px 0;">
                    <input type="checkbox" name="rfi_allowed_post_types[]" value="<?php echo $pt->name; ?>" 
                        <?php checked(in_array($pt->name, $selected)); ?>>
                    <?php echo $pt->labels->name; ?>
                </label>
            <?php endforeach; ?>
        </div>
        <p class="description">选择需要生效的文章类型</p>
        <?php
    }

    // ======================== 批量操作 ========================
    /**
     * 添加批量操作选项
     */
    public function add_bulk_action($bulk_actions) {
        $bulk_actions['random_thumbnail'] = '随机设置特色图片';
        return $bulk_actions;
    }

    /**
     * 处理批量操作
     */
    public function handle_bulk_action() {
        // 检查权限
        if (!current_user_can('edit_posts')) {
            wp_die('无权限执行此操作');
        }

        // 获取选中的文章 ID
        if (!isset($_REQUEST['post'])) {
            return;
        }

        $post_ids = array_map('intval', $_REQUEST['post']);
        foreach ($post_ids as $post_id) {
            $this->set_random_thumbnail($post_id);
        }

        // 跳转回文章列表
        $redirect = add_query_arg(
            array(
                'post_type' => $_REQUEST['post_type'],
                'updated'   => count($post_ids)
            ),
            admin_url('edit.php')
        );
        wp_redirect($redirect);
        exit;
    }
}

// 初始化插件
new Random_Featured_Image();

// 添加批量操作成功提示
add_action('admin_notices', function() {
    if (isset($_GET['updated']) && intval($_GET['updated']) > 0) {
        echo '<div class="notice notice-success is-dismissible">
            <p>已为 ' . intval($_GET['updated']) . ' 篇文章随机设置特色图片</p>
        </div>';
    }
});

使用步骤

  1. 创建图片目录:在 wp-content/uploads/ 下创建 random-thumb 目录(或自定义目录),并上传需要随机展示的图片
  2. 安装插件
    • 将上述代码保存为 random-featured-image.php
    • 上传到 wp-content/plugins/ 目录
    • 在 WordPress 后台「插件」页面启用「随机特色图片」插件
  3. 配置插件
    • 进入「设置」→「随机特色图片」
    • 可设置是否自动生成、图片目录、生效的文章类型
  4. 使用方式
    • 自动模式:保存文章时自动为无特色图片的文章分配随机图片
    • 手动批量:在文章列表中选择多篇文章,批量操作选择「随机设置特色图片」

进阶优化(可选)

  1. 缓存优化:可缓存图片列表,避免每次都扫描目录
  2. 排除特定分类:可添加设置项排除特定分类的文章
  3. 图片尺寸:可自动裁剪图片为指定尺寸后再设置为特色图片
  4. 重复检测:可避免同一篇文章重复设置相同的随机图片

注意事项

  1. 确保图片目录有可读权限(推荐 755)
  2. 图片文件名称建议使用英文 / 数字,避免中文乱码
  3. 批量操作时建议分批处理(如每次 100 篇),避免超时
  4. 如果需要替换已有特色图片,可注释代码中 if (has_post_thumbnail($post_id)) 相关判断

在上述自定义插件中,已内置两种手动触发重新随机设置特色图片的方式(单篇 / 批量),以下是详细操作步骤和扩展方法:

一、批量触发(推荐,适合多文章)

适用于需要为多篇文章重新分配随机特色图片的场景,操作步骤:

  1. 登录 WordPress 后台 → 进入「文章」(或其他生效的文章类型)列表页;
  2. 勾选需要重新设置特色图片的文章(可勾选全选框批量选择);
  3. 点击顶部「批量操作」下拉菜单,选择「随机设置特色图片」;
  4. 点击「应用」按钮,插件会自动为选中的文章重新随机分配特色图片(即使已有特色图片也会替换)。

关键说明:

  • 插件默认逻辑:如果文章已有特色图片,set_random_thumbnail() 方法中原本有 if (has_post_thumbnail($post_id)) return; 会跳过,如需强制替换,需修改代码:打开插件文件 random-featured-image.php,找到以下代码:
// 如果已有特色图片,跳过(可根据需求修改)
if (has_post_thumbnail($post_id)) {
    // 如需强制替换已有图片,注释上面的判断,取消下面注释
    // delete_post_thumbnail($post_id);
    return;
}

修改为:

// 强制替换已有特色图片
if (has_post_thumbnail($post_id)) {
    delete_post_thumbnail($post_id); // 删除原有特色图片
}

二、单篇文章触发(适合单篇调整)

方式 1:编辑文章时手动触发

  1. 进入单篇文章的「编辑」页面;
  2. 先删除当前特色图片(点击特色图片区域 → 「移除特色图片」);
  3. 点击「更新」按钮保存文章,插件会自动为其分配新的随机特色图片(需确保插件设置中「自动设置特色图片」为「是」)。

方式 2:添加快捷按钮(扩展优化)

如需在文章列表页为单篇文章添加「重新随机特色图片」快捷操作,可在插件中添加以下代码(插入到 Random_Featured_Image 类的 __construct 中):

// 添加单篇文章快速操作按钮
add_filter('post_row_actions', array($this, 'add_quick_action'), 10, 2);
// 处理单篇快速操作
add_action('admin_action_rfi_single_refresh', array($this, 'handle_single_action'));

然后在类中新增两个方法:

/**
 * 文章列表添加快速操作按钮
 */
public function add_quick_action($actions, $post) {
    // 仅对允许的文章类型显示
    $allowed_post_types = get_option('rfi_allowed_post_types', array('post'));
    if (!in_array($post->post_type, $allowed_post_types)) {
        return $actions;
    }
    // 添加「重新随机特色图片」按钮
    $nonce = wp_create_nonce('rfi_single_nonce_' . $post->ID);
    $actions['rfi_refresh'] = '<a href="' . admin_url('admin.php?action=rfi_single_refresh&post_id=' . $post->ID . '&_wpnonce=' . $nonce) . '" title="重新随机设置特色图片">重新随机特色图片</a>';
    return $actions;
}

/**
 * 处理单篇文章快速操作
 */
public function handle_single_action() {
    // 权限和安全验证
    if (!current_user_can('edit_posts') || !isset($_GET['post_id']) || !wp_verify_nonce($_GET['_wpnonce'], 'rfi_single_nonce_' . $_GET['post_id'])) {
        wp_die('操作无效或无权限');
    }
    $post_id = intval($_GET['post_id']);
    // 强制删除原有特色图片并重新分配
    delete_post_thumbnail($post_id);
    $this->set_random_thumbnail($post_id);
    // 跳转回文章列表
    wp_redirect(add_query_arg(array(
        'post_type' => get_post_type($post_id),
        'rfi_refreshed' => 1
    ), admin_url('edit.php')));
    exit;
}

最后添加提示语(插件末尾):

// 单篇操作成功提示
add_action('admin_notices', function() {
    if (isset($_GET['rfi_refreshed']) && intval($_GET['rfi_refreshed']) === 1) {
        echo '<div class="notice notice-success is-dismissible">
            <p>已为该文章重新随机设置特色图片</p>
        </div>';
    }
});

添加后,文章列表每篇文章的「快速操作」中会出现「重新随机特色图片」按钮,点击即可一键重新分配。

三、手动触发的核心逻辑说明

无论批量还是单篇,手动触发的核心是调用插件的 set_random_thumbnail($post_id) 方法:

  1. 先验证文章类型是否允许;
  2. 可选删除原有特色图片(强制替换);
  3. 扫描指定目录获取图片列表,随机选一张;
  4. 将图片添加到媒体库并设置为新的特色图片。

四、常见问题解决

  1. 点击后无反应:检查图片目录是否有图片、目录权限(755)、PHP 扫描目录权限;
  2. 特色图片未替换:确认已注释 / 删除 has_post_thumbnail 的跳过逻辑;
  3. 权限错误:确保当前用户有「编辑文章」和「上传文件」权限。