Use a separate upload folder for custom post attachment upload

I ended up solving it by completely bypassing the wp upload system, so this is how it looks now:

/*
 * 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 . "https://wordpress.stackexchange.com/" . $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');

It’s well less ugly than what i had before, but still would be much better if this could be done using the upload_dir filter.

Leave a Comment