Changing upload directory for plugin uploads only

I’ve spent a lot of time reading the other threads on this question, but I just cannot get my code to function properly.

I’m building a plugin, and I’ve set up an upload form on my custom admin page, and I am using Media Uploader to process the upload. Please see below for simplified code:

Read More
class myPlugin() {
  function __construct(){
    add_filter('wp_handle_upload_prefilter', array( $this, 'handle_upload_prefilter') );
    add_filter('wp_handle_upload', array( $this, 'handle_upload') );
  }

  function handle_upload_prefilter( $file ) {
    add_filter('upload_dir', array( $this, 'custom_upload_dir' ) );
    return $file;
  }

  function handle_upload( $fileinfo )   {
    remove_filter('upload_dir', array( $this, 'custom_upload_dir' ) );
    return $fileinfo;
  }

  function custom_upload_dir($args) {   
    $args['path'] = $args['basedir'] . "/mypath" . $args['subdir'];
    $args['url'] = $args['baseurl'] . "/mypath" . $args['subdir'];
    return $args;
  }
}

The code above works, and it changes the upload directory to the path that I specify. However, it is changing the upload directory for ALL uploads. I’d like my code to run only when uploading from my custom admin page.

This is what I’ve tried so far (and has not worked for me):

  1. I’ve tried using conditionals to test for $pagenow and get_current_screen in my custom_upload_dir function, but that seems to fail every time and uses the default upload paths.
  2. I’ve tried testing for conditional in my __construct but I get returned an error (I guess it’s too early in the WP lifecycle).
  3. Tried running the conditional in my handle_upload_prefilter function also to no avail.

Related posts

1 comment

  1. There must be something identifiable about your form data, such as your input names. Check for one or more of those and process accordingly.

    function custom_upload_dir($args) {   
        if (isset($_POST['something'])) {
            $args['path'] = $args['basedir'] . "/mypath" . $args['subdir'];
            $args['url'] = $args['baseurl'] . "/mypath" . $args['subdir'];
        }
        return $args;
    }
    

    After some investigation, the only things I see that might help are …

    1. The post ID is passed through the POST data to the callback.
      However I don’t know this would be set to in you custom plugin page.
    2. $_SERVER['HTTP_REFERER'] appears to be set correctly. You could
      parse that to determine if your plugin page is the originating
      page.

    If I had the full plugin source I could do some testing.

Comments are closed.