How to Set Upload Directory for a Custom Post Type

I recently came across a very nifty piece of code (credits to jdenham) for setting the upload directory for a 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' );

If you enjoyed this post, make sure to subscribe to WP Mayor’s RSS feed.

About Jean Galea

Jean Galea is a WordPress developer, trainer and consultant. He is the founder of WP Mayor and is available for freelance work. You can get in touch via his website at www.jeangalea.com.

More from the Mayor:

  1. Using Featured Images in Custom Post Types
  2. How To Remove Media Upload Buttons in Post Editor
  3. The Ultimate Guide to WordPress Custom Post Types
  4. Guide to Using Custom Functions Plugins in WordPress
  5. How to Add Custom Image Sizes to WordPress Uploader

2 Responses

  1. Erik
    Erik February 13, 2012 at 13:07 | | Reply

    Awesome, nice trick!

    I tried to modify it a bit to work on a regular plugin. In this example I did a little plugin to register members of some kind and have the profile photos upload to the plugin dir just like in the original. Although this doesn’t seem to work, the files are still saved in the regular dir. Any ideas?

    The plugin itself uses a simple form to save data to db and I also hook the wp-uploader to upload and send the image url with the rest of the data.

    function custom_upload_directory( $args ) {

    $screen = get_current_screen();

    // If the parent_base is members, upload to plugin directory
    if ( $screen->parent_base == ‘members’ ) {
    $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’ );

  2. Thibaut
    Thibaut March 30, 2012 at 19:36 | | Reply

    Is it possible to change to upload directory only for some file types (e.g. for PDF files)?

Leave a Reply