• Hello guys,

    I want to change the upload folder dynamically but I just can’t find the solution.
    How can i change dynamic the folder /CUSTOM

    Code example in function

    
    function changeUploadFolder( $upload ) {
          $upload['subdir'] = '/CUSTOM' . $upload['subdir'];
          $upload['path'] = $upload['basedir'] . $upload['subdir'];
          $upload['url']  = $upload['baseurl'] . $upload['subdir'];
          return $upload;
    }
    
    add_filter('upload_dir', 'changeUploadFolder');
    ...
     //here the file is uploaded with the new dynamic path
    ...
    remove_filter('upload_dir', 'changeUploadFolder');
    

    Thx for help
    Alex

Viewing 3 replies - 1 through 3 (of 3 total)
  • I have done this (in testing) with getting the value from the POSTed variable in an AJAX call. There probably should be more sanitization:

    function changeUploadFolder( $upload ) {
      $mypath = trim( $_POST['mypath'] );  //sanitize this better!
      // only affect requests to original upload dir
      if ( stripos( $mypath, $upload['baseurl'] ) == 0 ) {
        $diff = str_replace( $upload['baseurl'] . '/', '', $mypath ) );
        $parts = pathinfo( $diff );
        $upload['subdir'] = $parts['dirname'] ? '/'.$parts['dirname'] : '';
        $upload['path'] = $upload['basedir'] . $upload['subdir'];
        $upload['url']  = $upload['baseurl'] . $upload['subdir'];
      }
      return $upload;
    }
    Thread Starter nirus

    (@nirus)

    Hey,
    thanks for this solution.

    I see, I forgot to write that I pass the new path without $ _POST,
    but determine it via a mysql query.

    is it possible to pass the new path into the function via a parameter?

    /CUSTOM –> $newPath

    an example:

    function changeUploadFolder( $upload ) {
          $upload['subdir'] = '/CUSTOM' . $upload['subdir'];
          $upload['path'] = $upload['basedir'] . $upload['subdir'];
          $upload['url']  = $upload['baseurl'] . $upload['subdir'];
          return $upload;
    }
    
    $newPath = $getNewFolder->show_newFolder() . '/' . $getNewSubFolder->show_NewSubFolder();
    
    add_filter('upload_dir', 'changeUploadFolder');
    ...
     //here the file is uploaded with the new dynamic path
    ...
    remove_filter('upload_dir', 'changeUploadFolder');
    
    • This reply was modified 4 years, 5 months ago by nirus.
    • This reply was modified 4 years, 5 months ago by nirus.
    • This reply was modified 4 years, 5 months ago by nirus.
    Moderator bcworkz

    (@bcworkz)

    Filter callbacks only get passed what the apply_filters() call passes to them. You cannot not add additional parameters. If your callback needs other variable data that’s not passed you need to obtain it through other means such as a global or static property.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘dynamic change of the upload folder’ is closed to new replies.