mercredi 25 mars 2015

Limit WP Uploader to certain file types only in pages


I have a page where I'm using the WP Editor and allowing users to insert images into posts. I'm trying to limit their ability to only add images and I do this with the following filter:



add_filter('wp_handle_upload_prefilter', 'yoursite_wp_handle_upload_prefilter');
function yoursite_wp_handle_upload_prefilter($file) {
// This bit is for the flash uploader
if ($file['type']=='application/octet-stream' && isset($file['tmp_name'])) {
$file_size = getimagesize($file['tmp_name']);
if (isset($file_size['error']) && $file_size['error']!=0) {
$file['error'] = "Unexpected Error: {$file_size['error']}";
return $file;
} else {
$file['type'] = $file_size['mime'];
}
}

list($category,$type) = explode('/',$file['type']);

if('image'!=$category || !in_array($type,array('jpg','jpeg','gif','png'))) {
$file['error'] = "Sorry, you can only upload a .GIF, a .JPG, or a .PNG image file.";
}

return $file;
}


This code is triggered when I try and add a zip file for a plugin in the admin dashboard for example and it won't let me do it because this code is triggered. I tried to add in a line to check if it is is_admin() and return and don't execute that code. The code then looked like this:



add_filter('wp_handle_upload_prefilter', 'yoursite_wp_handle_upload_prefilter');
function yoursite_wp_handle_upload_prefilter($file) {
// This bit is for the flash uploader
if( is_admin() ) return; //<--- Added this line
if ($file['type']=='application/octet-stream' && isset($file['tmp_name'])) {
$file_size = getimagesize($file['tmp_name']);
if (isset($file_size['error']) && $file_size['error']!=0) {
$file['error'] = "Unexpected Error: {$file_size['error']}";
return $file;
} else {
$file['type'] = $file_size['mime'];
}
}

list($category,$type) = explode('/',$file['type']);

if('image'!=$category || !in_array($type,array('jpg','jpeg','gif','png'))) {
$file['error'] = "Sorry, you can only upload a .GIF, a .JPG, or a .PNG image file.";
}

return $file;
}


When I update this I get the following error code when I try and upload an image:



`File is empty. Please upload something more substantial.`


How can I only limit the WP Editor to only images on the front end and in the admin section, not execute this code? Is there another filter to use?


Thanks





Aucun commentaire:

Enregistrer un commentaire