我尝试过这两种方法,但仍然收到错误消息:“对不起,出于安全原因,不允许使用此文件类型。”
// add support for webp mime types
function webp_upload_mimes( $existing_mimes ) {
// add webp to the list of mime types
$existing_mimes['webp'] = 'image/webp';
// return the array back to the function with our added mime type
return $existing_mimes;
}
add_filter( 'mime_types', 'webp_upload_mimes' );
function my_custom_upload_mimes($mimes = array()) {
// add webp to the list of mime types
$existing_mimes['webp'] = 'image/webp';
return $mimes;
}
add_action('upload_mimes', 'my_custom_upload_mimes');有什么想法吗?
发布于 2018-12-17 22:37:30
除了使用wp_check_filetype_and_ext过滤器将mime类型添加到可上传的mime列表之外,还需要使用upload_mimes过滤器来设置webp文件的mime类型和扩展名。
/**
* Sets the extension and mime type for .webp files.
*
* @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
* 'proper_filename' keys.
* @param string $file Full path to the file.
* @param string $filename The name of the file (may differ from $file due to
* $file being in a tmp directory).
* @param array $mimes Key is the file extension with value as the mime type.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse_file_and_ext_webp', 10, 4 );
function wpse_file_and_ext_webp( $types, $file, $filename, $mimes ) {
if ( false !== strpos( $filename, '.webp' ) ) {
$types['ext'] = 'webp';
$types['type'] = 'image/webp';
}
return $types;
}
/**
* Adds webp filetype to allowed mimes
*
* @see https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes
*
* @param array $mimes Mime types keyed by the file extension regex corresponding to
* those types. 'swf' and 'exe' removed from full list. 'htm|html' also
* removed depending on '$user' capabilities.
*
* @return array
*/
add_filter( 'upload_mimes', 'wpse_mime_types_webp' );
function wpse_mime_types_webp( $mimes ) {
$mimes['webp'] = 'image/webp';
return $mimes;
}我在WPv5.0.1上测试了这一点,并在添加这段代码之后能够上传webp文件。
发布于 2018-12-17 22:16:08
有时上传会受到主机的限制。尝试并定义允许上载每个文件类型的ALLOW_UNFILTERED_UPLOADS常量:
define( 'ALLOW_UNFILTERED_UPLOADS', true );为了测试目的,请在wp-config.php文件中使用这一点。然后重新上传你的文件,如果它仍然不工作,很可能是主机阻止了该文件类型被上传。当您完成尝试时,请确保尽快删除该常量。
此外,还可以使用get_allowed_mime_types()函数检查允许的上载mimes。
发布于 2019-10-08 07:07:23
通过创建下面的插件,我能够让它工作起来。(您只需将此代码添加到/wp-content/plugins/目录中的一个新文件中,即可创建插件。确保在创建插件后激活它。)
https://wordpress.stackexchange.com/questions/323221
复制相似问题