钩子文档

upload_mimes

💡 云策文档标注

概述

upload_mimes 是一个 WordPress 过滤器,用于修改允许上传的 MIME 类型和文件扩展名列表。开发者可以通过此 Hook 添加、移除或调整文件上传限制,以适应特定需求。

关键要点

  • upload_mimes 过滤器接收两个参数:$t(MIME 类型数组,键为文件扩展名正则表达式)和 $user(用户 ID、用户对象或 null)。
  • 此过滤器常用于扩展 WordPress 默认支持的文件类型,如 SVG、JSON、CSV、字体文件或 WebP 图像。
  • 通过 add_filter 函数挂载自定义回调函数,修改 $mimes 数组并返回,即可生效。

代码示例

// 添加自定义 MIME 类型示例
function my_custom_mime_types( $mimes ) {
    // 添加新类型
    $mimes['svg'] = 'image/svg+xml';
    $mimes['json'] = 'application/json';
    // 可选:移除类型
    unset( $mimes['exe'] );
    return $mimes;
}
add_filter( 'upload_mimes', 'my_custom_mime_types' );

注意事项

  • 确保 MIME 类型与文件扩展名匹配正确,避免安全风险。
  • 在某些本地环境(如 XAMPP)中,可能需要配置 PHP 扩展(如 GD)以支持特定文件类型(如 WebP)。
  • 使用匿名函数或闭包时,注意代码兼容性和可读性。

📄 原文内容

Filters the list of allowed mime types and file extensions.

Parameters

$tarray
Mime types keyed by the file extension regex corresponding to those types.
$userint|WP_User|null
User ID, User object or null if not provided (indicates current user).

Source

return apply_filters( 'upload_mimes', $t, $user );

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Add MIME types.

    function my_custom_mime_types( $mimes ) {
    	
    	// New allowed mime types.
    	$mimes['svg']  = 'image/svg+xml';
    	$mimes['svgz'] = 'image/svg+xml';
    	$mimes['doc']  = 'application/msword'; 
    
        // Optional. Remove a mime type.
        unset( $mimes['exe'] );
    
    	return $mimes;
    }
    
    add_filter( 'upload_mimes', 'my_custom_mime_types' );

  2. Skip to note 12 content

    // To upload photos in format WebP
    
    function wpdocs_custom_mime_types( $mimes ) {
    	
    	// New allowed mime types.
    	$mimes['webp'] = 'image/webp';
    
    	return $mimes;
    }
    
    add_filter( 'upload_mimes', 'wpdocs_custom_mime_types' );

    If you work locally, for example on XAMPP, you should also include extension=gd in php.ini, just uncomment it, removing ; in front of it.