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. |
Skip to note 7 content
Mahesh Waghmare
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' );<?php function svgz_mime_types( $mimes ) { // SVGZ allowed mime types. $mimes['svgz'] = 'application/x-gzip'; return $mimes; } add_filter( 'upload_mimes', 'svgz_mime_types' ); ?>And if you want to know what is your real file mime type, you can use this service: https://wp-check-mime-type.com/.
Skip to note 8 content
Jb Audras
(example taken from @dotmastaz’s feedback)
Allow SVGZ mime type:
And if you want to know what is your real file mime type, you can use this service: https://wp-check-mime-type.com/.
Skip to note 9 content
Justin Kopepasah
Filter the upload mime types to allow JSON files.
'text/plain' ) ); } );Skip to note 10 content
Shoaib Ali
Allow CSV file type.
function extend_mime_types( $types ) { $types['csv'] = 'text/csv'; return $types; } add_filter( 'upload_mimes', 'extend_mime_types' );Skip to note 11 content
thejaydip
Allow uploading fonts files.
function wpdocs_allow_mime_types( $mimes ) { $mimes['ttf'] = 'font/ttf'; $mimes['woff'] = 'font/woff'; $mimes['woff2'] = 'font/woff2'; } return $mimes; } add_filter( 'upload_mimes', 'wpdocs_allow_mime_types' );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.