Используйте отдельную папку загрузки для загрузки пользовательских вложений сообщений
Итак, я пытаюсь найти способ использовать две отдельные папки для загрузки, по умолчанию одна wp-content/uploads
для общих загрузок мультимедиа, а другая, скажем, wp-content/custom
для одного определенного типа вложений (PDF-файлы, прикрепленные к одному определенному типу post_type).
Важно разделять их как для организации, так и для безопасности данных, так как файлы PDF будут содержать несколько конфиденциальных данных, которые должны быть доступны только двум пользовательским ролям пользователей, в то время как общие носители, ну, главный.
Мне немного неловко показывать вам код, который у меня работает, потому что он паршивый, но вот он:
function custom_post_type_metabox_save_function($post_id) {
global $post;
// Verify auto-save, nonces, permissions and so on then:
update_post_meta($post_id, "meta_key1", $_POST["value1"]);
update_post_meta($post_id, "meta_key2", $_POST["value2"]);
// this is where it gets uply. I change the 'upload_path' to my desired one for this post type
update_option('upload_path','wp-content/custom-upload-dir');
// then upload the file to it
wp_upload_bits($_FILES["pdfexame"]["name"], null, file_get_contents($_FILES["pdfexame"]["tmp_name"]));
// and then change it back to default... :$
update_option('upload_path','');
}
add_action('save_post','custom_post_type_metabox_save_function');
Я бы предпочел просто загрузить 2 файла, один для этого формата, а другой для остальных. Есть ли более чистый способ сделать это?
1 answers
В итоге я решил эту проблему, полностью обойдя систему загрузки wp, так что теперь это выглядит так:
/*
* Define new upload paths
*/
$uploadfolder = WP_CONTENT_DIR . '/exames'; // Determine the server path to upload files
$uploadurl = content_url() . '/exames/'; // Determine the absolute url to upload files
define(RM_UPLOADDIR, $uploadfolder);
define(RM_UPLOADURL, $uploadurl);
function custom_post_type_metabox_save_function($post_id) {
global $post;
// Verify auto-save, nonces, permissions and so on then:
update_post_meta($post_id, "meta_key1", $_POST["value1"]);
update_post_meta($post_id, "meta_key2", $_POST["value2"]);
update_post_meta($post_id, "meta_key3", $_POST["value3"]);
$destination = RM_UPLOADDIR; // Determine the path to upload files
$filename = $_FILES["file"]["name"]; // Get the uploaded file name
// This separates the extension from the rest of the file name
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
$newname = time() . rand(); // Create a new name
$filepath = $destination . '/' . $newname.'.'.$exts; // Get the complete file path
$filename = $newname.'.'.$exts; // Get the new name with the extension
// Now, if the upload was successful we save a post meta with the filename, if not, save nothing
if (move_uploaded_file($_FILES["pdfexame"]["tmp_name"], $filepath)) {
update_post_meta($post_id, "rm_martins_exame_url", $filename);
}
}
add_action('save_post','custom_post_type_metabox_save_function');
Это намного менее уродливо, чем то, что было у меня раньше, но все же было бы намного лучше, если бы это можно было сделать с помощью фильтра upload_dir
.