How to change the upload directory of uploaded files?
-
I created a custom page template with a form. The user can input his/her basic info and upload a file. Now, I have a PHP function that will upload the file in the default upload folder, but I want to save the uploaded files in other directory path (E.g. outside wp-content) and I want to rename in my own format, like lastname_firstname of the user who upload the file.
$attachment_id
is very important to me because this is the only way to call the file name and retrieve the file with download link.Please help me
function upload_user_file($file = array()){ require_once(ABSPATH . 'wp-admin/includes/admin.php'); $file_return = wp_handle_upload($file, array('test_form' => false)); if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){ return false; } else { $filename = $file_return['file']; $attachment = array( 'post_mime_type' => $file_return['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit', 'guid' => $file_return['url'] ); $attachment_id = wp_insert_attachment($attachment, $file_return['url']); require_once(ABSPATH . 'wp-admin/includes/file.php'); $attachment_data = wp_generate_attachment_metadata($attachment_id, $filename); wp_update_attachment_metadata($attachment_id, $attachment_data); if(0 < intval($attachment_id)){ return $attachment_id; } } return false; }
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘How to change the upload directory of uploaded files?’ is closed to new replies.