X

How to Restrict Image Uploads by Types in WordPress

Snippets by IsItWP

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.

Comments   Leave a Reply

  1. 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

  2. Thanks

  3. 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

    1. You could add this line to the $mimes variable:
      ‘mp3’ => ‘audio/mpeg’,

  4. how about user role? Thank you for the article.

  5. how about user role? Thank you for the article.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!