Last active
August 26, 2021 13:14
-
-
Save rianrietveld/8705908 to your computer and use it in GitHub Desktop.
Add custom post type name to upload directory WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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