使用单独的上传文件夹进行自定义帖子附件上传


9

因此,我正在尝试找到一种使用两个单独的上传文件夹的方法,这是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个上传文件,其中一个用于这种后期格式,而另一个用于其他格式。有没有更清洁的方法可以解决?

Answers:


4

我最终通过完全绕过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过滤器完成,那还是会更好。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.