How to add more upload directories?

The following code will change the upload directory for a specific post-type!

Just be sure to swap out both instances of “post-type” (line 14) with the name of your custom post-type.

/**
 * Change Upload Directory for Custom Post-Type
 * 
 * This will change the upload directory for a custom post-type. Attachments will
 * now be uploaded to an "uploads" directory within the folder of your plugin. Make
 * sure you swap out "post-type" in the if-statement with the appropriate value...
 */
function custom_upload_directory( $args ) {

    $id = $_REQUEST['post_id'];
    $parent = get_post( $id )->post_parent;

    // Check the post-type of the current post
    if( "post-type" == get_post_type( $id ) || "post-type" == get_post_type( $parent ) ) {
        $args['path'] = plugin_dir_path(__FILE__) . "uploads";
        $args['url']  = plugin_dir_url(__FILE__) . "uploads";
        $args['basedir'] = plugin_dir_path(__FILE__) . "uploads";
        $args['baseurl'] = plugin_dir_url(__FILE__) . "uploads";
    }
    return $args;
}
add_filter( 'upload_dir', 'custom_upload_directory' );

This was made to work with plugins, but could be modified for use in themes. Hope this helps, let me know if you have any questions!

== UPDATE ==

I forgot to mention, if you’d like to use WordPress’ default year/month method of organizing the uploads folder, simply change lines 15 and 16 to the following:

$args['path'] = plugin_dir_path(__FILE__) . "uploads" . $args['subdir'];
$args['url']  = plugin_dir_url(__FILE__) . "uploads" . $args['subdir'];

Leave a Comment