Используйте отдельную папку для загрузки для загрузки пользовательских сообщений
Итак, я пытаюсь найти способ использовать две отдельные папки для загрузки, по умолчанию один wp-content/uploads
для общих носителей 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 ответ
Я решил решить это, полностью обойдя систему загрузки 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
.