Custom Upload Directory
By default, WordPress uses the same uploads folder for every uploaded media, no matter who uploads it, where they upload it from or the type of media it is. This can cause problems for larger sites with lots of uploaded media, especially when many image sizes are created by WordPress. It can not only be a headache to go through manually, it can actually slow down your site (if those folders have thousands of images each).
But, its really not too hard to better organize those uploads into folders that you control, based on the above criteria. I use it to keep media associated with my portfolio page better organized.
This example has set a folder for each Custom Post Type. With some simple tweaking, this can also be used for usernames, multisites, media type, post category or anything else you can think of.
Place the following in functions.php or create a plugin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // Custom Upload Directories for Post Types add_filter( 'upload_dir', 'custom_upload_directory' ); function custom_upload_directory( $args ) { $id = $_REQUEST['post_id']; $parent = get_post( $id )->post_parent; $slug = get_post( $id )->post_name; // Check the post-type of the current post // assign directory to upload to // assign URL to connect to if( "web-design" == get_post_type( $id ) || "web-design" == get_post_type( $parent ) ) { $args['path'] = WP_CONTENT_DIR . '/uploads/web-design/' . $slug . ''; $args['url'] = WP_CONTENT_URL . '/uploads/web-design/' . $slug . ''; } if( "photograph" == get_post_type( $id ) || "photograph" == get_post_type( $parent ) ) { $args['path'] = WP_CONTENT_DIR . '/uploads/photograph/' . $slug . ''; $args['url'] = WP_CONTENT_URL . '/uploads/photograph/' . $slug . ''; } if( "other-artwork" == get_post_type( $id ) || "other-artwork" == get_post_type( $parent ) ) { $args['path'] = WP_CONTENT_DIR . '/uploads/other-artwork/' . $slug . ''; $args['url'] = WP_CONTENT_URL . '/uploads/other-artwork/' . $slug . ''; } return $args; } |