I’ve tried both of these, but I’m still getting the error message: “Sorry, this file type is not permitted for security reasons.”

// 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');

Any ideas?

3 s
3

It’s necessary to use the wp_check_filetype_and_ext filter to set the mime type and extension for webp files in addition to using the upload_mimes filter to add the mime type to the list of uploadable mimes.

/**
 * 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;
}

I tested this on WP v5.0.1 and was able to upload webp files after adding this code.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *