9

I am trying to work out how to use the wp_handle_upload function for a custom plugin so that i can specify my own own upload directory. The code so far takes a file from my plugin settings page and uploads to the folder uploads folder with the year and month.

I came across this link which I thought might have some clues - http://yoast.com/smarter-upload-handling-wp-plugins

if(strtolower($_SERVER['REQUEST_METHOD']) == "post"){

     $overrides = array('test_form' => false);
     $file = wp_handle_upload($_FILES['binaryFile'], $overrides);

     echo "<pre>" . print_r($file, true) . "</pre>";
}

How can I upload to a directory of my choosing?

Any help much appreciated guys.

5

Here's a complete example for how we do it in Easy Digital Downloads:

/**
 * Set Upload Directory
 *
 * Sets the upload dir to edd. This function is called from
 * edd_change_downloads_upload_dir()
 *
 * @since 1.0
 * @return array Upload directory information
*/
function edd_set_upload_dir( $upload ) {
    $upload['subdir'] = '/edd' . $upload['subdir'];
    $upload['path'] = $upload['basedir'] . $upload['subdir'];
    $upload['url']  = $upload['baseurl'] . $upload['subdir'];
    return $upload;
}


/**
 * Change Downloads Upload Directory
 *
 * Hooks the edd_set_upload_dir filter when appropriate. This function works by
 * hooking on the WordPress Media Uploader and moving the uploading files that
 * are used for EDD to an edd directory under wp-content/uploads/ therefore,
 * the new directory is wp-content/uploads/edd/{year}/{month}. This directory
 * provides protection to anything uploaded to it.
 *
 * @since 1.0
 * @global $pagenow
 * @return void
 */
function edd_change_downloads_upload_dir() {
    global $pagenow;

    if ( ! empty( $_REQUEST['post_id'] ) && ( 'async-upload.php' == $pagenow || 'media-upload.php' == $pagenow ) ) {
        if ( 'download' == get_post_type( $_REQUEST['post_id'] ) ) {
            add_filter( 'upload_dir', 'edd_set_upload_dir' );
        }
    }
}
add_action( 'admin_init', 'edd_change_downloads_upload_dir', 999 );
  • Note, we only modify the upload directory when uploading files from our Downloads custom post type page. You will need to adjust it for your plugin's settings page. – Pippin Jun 9 '13 at 3:37
  • It lacks "]" with $upload['url' – Mario Radomanana Mar 25 '14 at 9:08
1

I don't remember doing exactly this in practice, but most (all?) upload path handling goes through wp_upload_dir() that applies upload_dir filter to returned information. You should try filtering it for the duration of your code running and adjusting paths to wanted location.

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.