Skip to content

Instantly share code, notes, and snippets.

@kirandash
Created December 8, 2016 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kirandash/5e3c333375a465ba48e7e20069b5aa2b to your computer and use it in GitHub Desktop.
Save kirandash/5e3c333375a465ba48e7e20069b5aa2b to your computer and use it in GitHub Desktop.
WordPress File Upload using wp_handle_upload - change wordpress upload directory and change file name
require_once(ABSPATH.'wp-admin/includes/file.php');
$uploadedfile = $_FILES['csvtoimport'];
add_filter( 'upload_dir', 'wpse_183245_upload_dir' );
function wpse_183245_upload_dir( $dirs ) {
$dirs['subdir'] = '/upload';
$dirs['path'] = $dirs['basedir'] . '/upload';
$dirs['url'] = $dirs['baseurl'] . '/upload';
return $dirs;
}
add_filter( 'sanitize_file_name', 'so_3261107_hash_filename', 10 );
function so_3261107_hash_filename( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
return 'storelocator'.$ext;
}
$movefile = wp_handle_upload($uploadedfile, array('test_form' => false,'mimes' => array('csv' => 'text/csv') ));
remove_filter( 'sanitize_file_name', 'so_3261107_hash_filename', 10 );
remove_filter( 'upload_dir', 'wpse_183245_upload_dir' );
if ( $movefile ){
header("Location: admin.php?page=functions.php&saved=true");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment