Skip to content

Instantly share code, notes, and snippets.

@rianrietveld
Last active August 26, 2021 13:14
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save rianrietveld/8705908 to your computer and use it in GitHub Desktop.
Save rianrietveld/8705908 to your computer and use it in GitHub Desktop.
Add custom post type name to upload directory WordPress
<?php
/**
* Change Upload Directory for one Custom Post-Type
*
* This will change the upload directory for a custom post-type. Attachments for this custom post type will
* now be uploaded to a seperate "uploads" directory. Make
* sure you swap out "post-type" and the "my-dir" with the appropriate values...
* credits to: http://wordpress.stackexchange.com/users/4044/jhdenham
* and http://yoast.com/smarter-upload-handling-wp-plugins/
*/
add_filter('upload_dir', 'rrwd_upload_dir');
$upload = wp_upload_dir();
// remove_filter('upload_dir', 'rrwd_upload_dir');
function rrwd_upload_dir( $upload ) {
$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 ) )
$upload['subdir'] = '/my-dir' . $upload['subdir'];
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
?>
@waleedt93
Copy link

waleedt93 commented Feb 5, 2019

It works like a charm!
But it works when thumbnail support of CPT is enabled. Upon removing thumbnail support and uploading media through custom meta field it returns URL www.example.com/file-name/
Any help would be great. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment