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

WordPress上传图片时如何选择生成指定自定义尺寸?

解决方案:上传图片时选择生成指定自定义尺寸类别

直接通过WordPress原生钩子实现,无需插件,分三步完成:

1. 在媒体上传/编辑界面添加尺寸类别选择框

这段代码会在媒体库的图片编辑界面添加单选控件,让你选择要生成A类还是B类尺寸:

// 向媒体上传界面添加尺寸类别选择控件
add_filter('attachment_fields_to_edit', 'add_image_size_category_selector', 10, 2);
function add_image_size_category_selector($form_fields, $post) {
    $selected = get_post_meta($post->ID, '_image_size_category', true);
    
    $form_fields['image_size_category'] = [
        'label' => '尺寸类别',
        'input' => 'html',
        'html' => sprintf(
            '<label><input type="radio" name="attachments[%d][image_size_category]" value="A" %s> A类(img-a-sm、img-a-md)</label><br>
            <label><input type="radio" name="attachments[%d][image_size_category]" value="B" %s> B类(img-b-sm、img-b-lg)</label>',
            $post->ID, checked($selected, 'A', false),
            $post->ID, checked($selected, 'B', false)
        ),
        'helps' => '选择后仅生成对应类别的尺寸,减少冗余文件'
    ];
    
    return $form_fields;
}

2. 保存用户选择的尺寸类别

将用户的选择存储到图片附件的元数据中,后续生成尺寸时会读取这个值:

// 保存尺寸类别选择到附件元数据
add_filter('attachment_fields_to_save', 'save_image_size_category', 10, 2);
function save_image_size_category($post, $attachment) {
    if (isset($attachment['image_size_category'])) {
        update_post_meta($post['ID'], '_image_size_category', sanitize_text_field($attachment['image_size_category']));
    }
    return $post;
}

3. 过滤生成的图片尺寸,仅保留选中类别

通过钩子拦截图片生成流程,根据用户选择移除不需要的尺寸:

// 过滤图片生成尺寸,仅保留选中类别的自定义尺寸
add_filter('intermediate_image_sizes_advanced', 'filter_image_sizes_by_selected_category', 10, 3);
function filter_image_sizes_by_selected_category($sizes, $metadata, $attachment_id) {
    $selected_category = get_post_meta($attachment_id, '_image_size_category', true);
    
    // 未选择类别时,移除所有自定义尺寸(可根据需求调整默认行为)
    if (empty($selected_category)) {
        unset($sizes['img-a-sm'], $sizes['img-a-md'], $sizes['img-b-sm'], $sizes['img-b-lg']);
        return $sizes;
    }
    
    // 根据选中类别保留对应尺寸
    if ($selected_category === 'A') {
        unset($sizes['img-b-sm'], $sizes['img-b-lg']);
    } elseif ($selected_category === 'B') {
        unset($sizes['img-a-sm'], $sizes['img-a-md']);
    }
    
    return $sizes;
}

注意事项

  • 确保你已经在functions.php中正确定义了自定义尺寸(比如add_image_size('img-a-sm', 300, 200, true);这类代码);
  • 上传图片时务必选择尺寸类别,否则不会生成任何自定义尺寸(可修改第三步的默认逻辑,比如默认生成A类);
  • 若上传后修改了尺寸类别,需要删除已生成的缩略图并重新上传,或自行编写代码触发重新生成。

内容的提问来源于stack exchange,提问作者Piotr Ciszewski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:00:29