如何将WordPress自定义文章类型(CPT)附件保存到独立文件夹
Got it, let's fix this so your CPT attachments save straight to wp-content/uploads/myfile instead of WordPress's default year/month subfolders. Using WordPress's native hooks is the cleanest, most maintainable way to do this—here's how to implement it:
Step 1: Use the upload_dir Filter to Override Paths
WordPress provides the upload_dir filter to modify where uploads are stored. We'll use this hook to target only attachments uploaded for your custom post type, so it won't mess with other content like posts or pages.
Add this function to your plugin file:
function cpt_custom_upload_dir($dirs) { // Replace 'your_cpt_slug' with the actual slug of your custom post type $target_cpt = 'your_cpt_slug'; // Check if we're uploading from the CPT edit screen (using the post_id from the upload request) if (isset($_POST['post_id']) && get_post_type($_POST['post_id']) === $target_cpt) { $custom_folder = 'myfile'; // Update the upload path and URL to point to our custom folder $dirs['path'] = $dirs['basedir'] . '/' . $custom_folder; $dirs['url'] = $dirs['baseurl'] . '/' . $custom_folder; $dirs['subdir'] = '/' . $custom_folder; // Create the folder if it doesn't exist (WordPress's wp_mkdir_p handles permissions correctly) if (!file_exists($dirs['path'])) { wp_mkdir_p($dirs['path']); } } return $dirs; } add_filter('upload_dir', 'cpt_custom_upload_dir');
Step 2: Ensure Your Save Function Uses Native WordPress Upload Logic
If your existing save_custom_meta_data function uses wp_handle_upload (the recommended way to handle uploads in WordPress), you don't need to modify that code at all—this filter will automatically redirect the upload to your myfile folder.
For reference, here's how a typical attachment handling block in your save function might look (if you're not already using this pattern):
// Inside your save_custom_meta_data function if (isset($_FILES['your_attachment_field']) && $_FILES['your_attachment_field']['error'] === UPLOAD_ERR_OK) { $upload_args = array('test_form' => false); $upload_result = wp_handle_upload($_FILES['your_attachment_field'], $upload_args); if ($upload_result && !isset($upload_result['error'])) { // Save the attachment URL or file path to your post meta update_post_meta($id, 'your_custom_attachment_key', $upload_result['url']); } }
Key Notes to Keep in Mind
- Target the Right CPT: Make sure you replace
your_cpt_slugwith the actual slug of your custom post type (e.g., if your CPT is called "portfolio", the slug is probablyportfolio). - Permissions: WordPress's
wp_mkdir_pwill create themyfilefolder with correct permissions (usually 755) as long as yourwp-content/uploadsdirectory has write access. - Testing: After adding the code, upload an attachment via your CPT's edit screen, then check
wp-content/uploads/myfileon your server to confirm the file was saved there. Also verify the attachment shows up correctly in the media library.
This approach is future-proof because it uses WordPress's core hooks instead of hardcoding paths, so it won't break if WordPress updates its upload handling logic.
内容的提问来源于stack exchange,提问作者Firefog

