
Restrict Mime Types on WordPress Media Upload
WordPress has changed the library in version 3.3 – which I think is an improvement. The restrictions in terms of file types remains and you can control them via hook. So you can limit or extend the file-types. Via two hooks, this is done quickly and there is a notification displayed in your backend which lists the allowed file types.
The following small Plugin may extend to different roles or authorization objects, so that you can upload, depending on the role, different types of files in the system – current_user_can()
.
Anyone interested in the currently allowed types, you can return the array of the first function or look into the function get_allowed_mime_types()
in wp-includes/functions.php
.
<?php /** * Plugin Name: Restrict mime types * Plugin URI: https://wpengineer.com/?p=2369 * Description: Restrict list of allowed mime types and file extensions. * Version: 1.0.0 * License: GPLv3 * Author: Frank Bültge * Author URI: http://bueltge.de/ */ // This file is not called from WordPress. We don't like that. ! defined( 'ABSPATH' ) and exit; // If the function exists this file is called as upload_mimes. // We don't do anything then. if ( ! function_exists( 'fb_restrict_mime_types' ) ) { add_filter( 'upload_mimes', 'fb_restrict_mime_types' ); /** * Retrun allowed mime types * * @see function get_allowed_mime_types in wp-includes/functions.php * @param array Array of mime types * @return array Array of mime types keyed by the file extension regex corresponding to those types. */ function fb_restrict_mime_types( $mime_types ) { $mime_types = array( 'pdf' => 'application/pdf', 'doc|docx' => 'application/msword', ); return $mime_types; } } // If the function exists this file is called as post-upload-ui. // We don't do anything then. if ( ! function_exists( 'fb_restrict_mime_types_hint' ) ) { // add to wp add_action( 'post-upload-ui', 'fb_restrict_mime_types_hint' ); /** * Get an Hint about the allowed mime types * * @return void */ function fb_restrict_mime_types_hint() { echo '<br />'; _e( 'Accepted MIME types: PDF, DOC/DOCX' ); } }
Very usefull to block users to upload BMP!