How to add more upload directories?

I have two types of files in my WordPress Media Library, one is for pictures and attachments from posts, the other is for attachments from a custom post type.

I want to organize them separately, use my plugin’s dir as basedir for the custom post type, while keep other files in WordPress’ default upload directory.

Read More

Is it possible to add one more basedir?

Related posts

Leave a Reply

1 comment

  1. 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'];