Skip to content

Instantly share code, notes, and snippets.

@sabbir1991
Last active November 23, 2017 18:50
Show Gist options
  • Save sabbir1991/1c33e81c151bdfc86f675d24f14d30b7 to your computer and use it in GitHub Desktop.
Save sabbir1991/1c33e81c151bdfc86f675d24f14d30b7 to your computer and use it in GitHub Desktop.
File Upload in WordPress in custom directory
<?php
function wp1982_handle_file_upload( $filename, $file_url ) {
add_filter( 'upload_dir', 'wp1982_customize_upload_dir', 10 );
$upload_file = wp_upload_bits( $filename, null, file_get_contents( $file_url ) );
remove_filter( 'upload_dir', 'wp1982_customize_upload_dir' , 10 );
if ( !$upload_file['error'] ) {
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => 0,
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );
if (!is_wp_error( $attachment_id )) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
return $attachment_id;
}
}
return 0;
}
function wp1982_customize_upload_dir( $upload ) {
$user_id = get_current_user_id();
$user = get_user_by( 'id', $user_id );
$dirname = $user_id . '-' . $user->user_login;
$upload['subdir'] = '/reserved/' . $dirname;
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
// call upload function
$file_doc = $_FILES['file_name'];
$filename = $file_doc['name'];
$file_url = $file_doc['tmp_name'];
wp1982_handle_file_upload( $filename, $file_url );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment