Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change upload directory in my plugin uploader

I have developed a plugin and in my plugin there is a custom media uploader. When i upload any file from my plugin uploader that file is uploaded and saved in WordPress default uploads/ folder.

But I want that when i upload file from my plugin uploader those files should be uploaded in a new folder inside Wordpress custom uploads folder so I search from google and found this code:

 <?php
     function upload_dir($dirs)                                    
{                                                             
        $dirs['subdir'] = '/my-uploads';                  
        $dirs['path'] = $dirs['basedir'] . '/my-uploads'; 
        $dirs['url'] = $dirs['baseurl'] . '/my-uploads';  

        return $dirs;                                         
}                                                             

add_filter('upload_dir', 'upload_dir');                       

   ?>

Now all files that are uploaded from (posts, pages etc) are also stored in that plugin folder.

I want that only those files which are uploaded from my plugin uploader should be saved in that my-folder, and rest of the files should be saved in WordPress default uploads folder...

like image 901
Aasma Zafar Avatar asked Jun 02 '16 12:06

Aasma Zafar


People also ask

How do I change the default location for uploading files?

Click the [Windows] button > choose "File Explorer." From the left side panel, right-click "Documents" > choose "Properties." Click [Apply] > Click [No] when prompted to automatically move all files to the new location > Click [OK].


2 Answers

Right before the uploading code, use

add_filter('upload_dir', 'upload_dir'); 

Then after your uploading code, use:

remove_filter('upload_dir', 'upload_dir'); 

That way, the filter only works for your plugin uploads and not on other places.

like image 170
Marcel de Hoog Avatar answered Oct 24 '22 17:10

Marcel de Hoog


You might need to handle the file processing yourself using plain PHP. When you process the form, try this:

$uploaddir = '/path/to/plugin/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

if( move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
    echo 'success!';
else
    echo 'fail!';

and use print_r($_FILES); to debug.

Be very, very careful though - you're potentially creating a security risk. see Secure PHP File Upload Script for more info on that.

like image 43
david_nash Avatar answered Oct 24 '22 18:10

david_nash