Skip to content

Instantly share code, notes, and snippets.

@rianrietveld
Last active August 26, 2021 13:14
Show Gist options
  • 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;
}
?>
@gruntek
Copy link

gruntek commented Jan 24, 2019

Thank you so much for posting this handy snippet! Exactly what I needed. Combined with the Orbisius Media Protector https://orbisius.com/products/wordpress-plugins/orbisius-wp-media-protector I was able to set up a protected folder for internal post type files while keeping the rest of the WP uploads public. Works just fine with files uploaded though custom fields from Toolset WP Types.

Do you know how to change protected folder for Orbisius Media Protector?

@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