0

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

  • Can I start a bounty on this to get more attention? – user1048676 Apr 9 '15 at 0:49
0

Try,

if ( is_admin() ) return $file;

instead. Basically you should always return the filtered content, otherwise you effectively have filtered the $file to nothing.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.