tyzenxebec
tyzenxebec

Reputation: 27

Wordpress: specify a custom upload folder for a plugin

I am using the Store file uploads for Contact Form 7 plugin to save photo uploads to the WordPress Media Library for a contest our business is running.

The default upload path is www.site.com/wp-content/uploads. We will have hundreds of entries into the contest and we would like all entries to reside in www.site.com/wp-content/uploads/photo-contest instead.

This plugin seems to get the default path correctly:

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

How do I proceed with making the uploads go to a custom folder from here? (sorry for the newb question!)

I have tried this...

$wp_upload_dir = wp_upload_dir('/photo-contest');

...but it doesn't seem to work.

Upvotes: 0

Views: 2868

Answers (1)

Leander De Mooij
Leander De Mooij

Reputation: 26

You can use the Wordpress Filesystem API. I've been wondering around for this same thing earlier. It seems it's best to not add your own folder to the upload directory but rather create your own directory inside the Wordpress content folder. I recommend placing the directory outside your plugin folders so you can keep whatever files even if your plugin is removed. Putting them inside the uploads folder might not be that bad but I would not recommend it as for example a user might be able to access it via the url like example.com/uploads/your-folder/your-file (When configured incorrectly).

Using the Wordpress Filesystem API:

function mycoolplugin_create_folder() {
    global $wp_filesystem;

    /* It is a Wordpress core file, that's why we manually include it */
    require_once ( ABSPATH . '/wp-admin/includes/file.php' );
    
    /* Just instantiate as follows */
    WP_Filesystem();

    $custom_folder = WP_CONTENT_DIR .'/my-awesome-folder';

    if ( $wp_filesystem->exists( $custom_folder ) ) {
        // Do something if the File or Folder exists...
    } else {
       // File or Folder doesn't exist so we create it, returns true if created, false if something went wrong
       $folder_created = $wp_filsystem->mkdir( $custom_folder );

       if( ! $folder_created ) return new \WP_Error( 'FilesysError', __( 'Failed to create a folder.', 'my_textdomain' ) );
    }
}

Now there is a whole lot more you can do here and this is just a simple example of what you can do with it. Remember you are responsible for your own sanitization of your data and securing it. Using the WP_Filesystem can really help well with that but it can be a bit tricky to configure when you start with it for the first time. For more info I recommend you check these links:

Upvotes: 1

Related Questions