問題描述

所以,我試圖找出一種方法來使用兩個單獨的上傳文件夾,作為一般媒體上傳的默認 wp-content/uploads,另一個説 wp-content/custom 用於一種特定類型的附件 (附在一個特定的 post_type 上的 PDF 文件) 。

對於組織和數據安全性來説,保持分離是很重要的,因為 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 個上傳文件是一個為這個 post-format,另一個為其餘。有沒有更清潔的方法去做呢?

最佳解決方案

我最終通過完全繞過 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 濾鏡來完成,那還好多了。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。