首页 > 解决方案 > Wordpress:允许上传媒体中的 zip 文件

问题描述

我需要将 .zip 文件上传到媒体。

在这里我试过

https://wordpress.stackexchange.com/questions/57603/is-it-possible-to-allow-zip-files-to-be-uploaded-in-wordpress

add_filter('upload_mimes', 'custom_upload_mimes');
function custom_upload_mimes ( $existing_mimes=array() ) {
    // add your extension to the mimes array as below
    $existing_mimes['zip'] = 'application/zip';
    $existing_mimes['gz'] = 'application/x-gzip';
    return $existing_mimes;
}

但它不适用于 Wordpress 5+ 或古腾堡编辑器

标签: phpwordpressmediawordpress-gutenberg

解决方案


由于 WordPress 版本 4.7.1 或更高版本,它为 mime 类型添加了一些额外的安全检查。只需在活动主题的 functions.php 中添加以下代码片段即可实现上述目的 -

function modify_upload_mimes ( $mimes_types ) {
    // add your extension to the mimes array as below
    $mimes_types['zip'] = 'application/zip';
    $mimes_types['gz'] = 'application/x-gzip';
    return $mimes_types;
}
add_filter( 'upload_mimes', 'modify_upload_mimes', 99 );

function add_allow_upload_extension_exception( $types, $file, $filename, $mimes ) {
    // Do basic extension validation and MIME mapping
    $wp_filetype = wp_check_filetype( $filename, $mimes );
    $ext         = $wp_filetype['ext'];
    $type        = $wp_filetype['type'];
    if( in_array( $ext, array( 'zip', 'gz' ) ) ) { // it allows zip files
        $types['ext'] = $ext;
        $types['type'] = $type;
    }
    return $types;
}
add_filter( 'wp_check_filetype_and_ext', 'add_allow_upload_extension_exception', 99, 4 );

欲了解更多信息,请访问我的博客链接


推荐阅读