bueltge
12/15/2011 - 11:40 AM

Restrict list of allowed mime types and file extensions.

Restrict list of allowed mime types and file extensions.

<?php
/**
 * Plugin Name: Restrict mime types
 * Plugin URI:  http://wpengineer.com/?p=2369
 * Description: Restrict list of allowed mime types and file extensions.
 * Version:     1.0.0
 * License:     GPLv3
 * Author:      Frank B&uuml;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' );
	}
}