Do you want to restrict image uploads by the image type for specific users? You can restrict certain users from uploading specified image types. When a username is not in the users’ array, then they will only be able to upload jpg, and gif images.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin.
This sample only allows jpg and gif images. Adding a new line in the $mimes
array for png, eg: 'png' => 'image/png'
, would then allow png images.
add_filter('upload_mimes','restrict_mime'); function restrict_mime($mimes) { global $current_user; get_currentuserinfo(); // change users in list $users = array( "ryan", "steven", "larry", "jerry" ); if (!in_array($current_user->user_login, $users)) { $mimes = array( 'jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', ); } return $mimes; }
Or, alternatively use this code for restricting mime types for all users. Add this code to your theme’s functions.php file or in a site-specific plugin.
add_filter('upload_mimes','restrict_mime'); function restrict_mime($mimes) { $mimes = array( 'jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', ); return $mimes; }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 62 best free WordPress blog themes or 7 best WordPress contact form plugins.
Hi. WordPress plugin editor says there is an error with second code:
syntax error, unexpected ”jpg|jpeg|jpe” (T_CONSTANT_ENCAPSED_STRING), expecting ‘)’
Can you review your code? Thanks
Thanks
Hi, can you update the code as I need to upload mp3 files also, how can I add mp3 in this array ?
Please, help thanks
You could add this line to the $mimes variable:
‘mp3’ => ‘audio/mpeg’,
how about user role? Thank you for the article.
how about user role? Thank you for the article.