0

Is there a convention on how to store media uploaded and used only by the plugin? Would that be /wp-content/uploads/plugin_name or should they be stored like the rest of the media (chronogically)? Especially if there will be a lot of images that could be categorised in folders easily (eg. plugin_name/players, plugin_name/clubs)?

If the answer is creating an own plugin folder in uploads, how would you approach changing the upload directory for media uploaded in plugin's admin page?

0

You can do something like this to create your own plugin upload folder in /wp-content/uploads the following code will basically create a custom folder inside uploads called myplugin_uploads and put an empty index.html inside it.

Dynamically creating your custom upload folder

add_action( 'init', 'create_files' );
function create_files() {

    $upload_dir      = wp_upload_dir();

    $files = array(
        array(
            'base'      => $upload_dir['basedir'] . '/myplugin_uploads',
            'file'      => 'index.html',
            'content'   => ''
        )
    );

    foreach ( $files as $file ) {
        if ( wp_mkdir_p( $file['base'] ) && ! file_exists( trailingslashit( $file['base'] ) . $file['file'] ) ) {
            if ( $file_handle = @fopen( trailingslashit( $file['base'] ) . $file['file'], 'w' ) ) {
                fwrite( $file_handle, $file['content'] );
                fclose( $file_handle );
            }
        }
    }

}

Now practically, you'll need to change the upload dir/destination. You can do so using the upload_dir filter hook.

Example

add_filter('upload_dir', 'myplugin_upload_dir');
function myplugin_upload_dir( $param ){
    $mydir = '/myplugin_uploads';

    $param['path'] = $param['path'] . $mydir;
    $param['url'] = $param['url'] . $mydir;

    return $param;
}

When you're done you can remove the filter with code:

remove_filter('upload_dir', 'myplugin_upload_dir');

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.