Change media upload folder of attachment based on post type/custom post type in Wordpress

Change media upload folder of attachment based on post type/custom post type in Wordpress

Posted: 7 years ago in  Wordpress | PHP |


In Wordpress, media files as images will be stored in wp-content/uploads. For website with many posts (create custom post type) / image size (create custom image size), number of images will grow up quickly and it will slow down the page load due to file lookup.


We can hook to Wordpress and separate the media folders. In this example, I use the post type that the image attached as folder name.

Let say we have the custom post type "project", when create Project post, we will set the featured image. It will be saved in wp-content/uploads/project instead of wp-content/uploads

Add this code snippet in functions.php of Wordpress theme or create a plugin to execute this filter

function custom_upload_directory( $args ) {
 $id = ( isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : '' );
 if( $id ) {
 $newdir = '/' . get_post_type( $id );
 $args['subdir'] = $newdir;
 $args['path'] .= $newdir; 
 $args['url'] .= $newdir;
 return $args;
 }
}
add_filter( 'upload_dir', 'custom_upload_directory' );

And if you want to limit this function to specific post type, use if statement

if( "specific-post-type" == get_post_type( $id ) )