I have two types of files in my WordPress Media Library, one is for pictures and attachments from posts, the other is for attachments from a custom post type.
I want to organize them separately, use my plugin’s dir as basedir for the custom post type, while keep other files in WordPress’ default upload directory.
Is it possible to add one more basedir?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The following code will change the upload directory for a specific post-type!
Just be sure to swap out both instances of “post-type” (line 14) with the name of your custom post-type.
/**
* Change Upload Directory for Custom Post-Type
*
* This will change the upload directory for a custom post-type. Attachments will
* now be uploaded to an "uploads" directory within the folder of your plugin. Make
* sure you swap out "post-type" in the if-statement with the appropriate value...
*/
function custom_upload_directory( $args ) {
$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 ) ) {
$args['path'] = plugin_dir_path(__FILE__) . "uploads";
$args['url'] = plugin_dir_url(__FILE__) . "uploads";
$args['basedir'] = plugin_dir_path(__FILE__) . "uploads";
$args['baseurl'] = plugin_dir_url(__FILE__) . "uploads";
}
return $args;
}
add_filter( 'upload_dir', 'custom_upload_directory' );
This was made to work with plugins, but could be modified for use in themes. Hope this helps, let me know if you have any questions!
== UPDATE ==
I forgot to mention, if you’d like to use WordPress’ default year/month method of organizing the uploads folder, simply change lines 15 and 16 to the following:
$args['path'] = plugin_dir_path(__FILE__) . "uploads" . $args['subdir']; $args['url'] = plugin_dir_url(__FILE__) . "uploads" . $args['subdir'];
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0