我想要更改文件上传名称并添加上传它的用户名 这是我的function.php
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
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{
$user = wp_get_current_user();
$username = $user->display_lastname;
$filename = $username . $file_return['file'];
return $filename;
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.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;
}
endif;
我尝试使用$ filename = $ username。 $ file_return [ '文件'];但是不行。
答案 0 :(得分:0)
wp_handle_upload
接受一组覆盖,其中一个参数是unique_filename_callback
,您可以在其中指定自定义函数来重命名该文件。
尝试这样的事情:
1:向functions.php添加一个函数,以根据需要重命名文件,例如
function my_custom_filename($dir, $name, $ext){
$user = wp_get_current_user();
/* You wanted to add display_lastname, but its not required by WP so might not exist.
If it doesn't use their username instead: */
$username = $user->display_lastname;
if (!$username) $username = $user->user_login;
$newfilename = $username ."_". $name; /* prepend username to filename */
/* any other code you need to do, e.g. ensure the filename is unique, remove spaces from username etc */
return $newfilename;
}
2:然后在upload_user_file()中,在wp_handle_upload覆盖中指定自定义回调函数,例如
$overrides = array(
'test_form' => false, /* this was in your existing override array */
'unique_filename_callback' => 'my_custom_filename'
);
/* pass your overrides array into wp_handle_upload */
$file_return = wp_handle_upload($file,$overrides);
更新:
要在upload_user_file
函数中获取新文件名,您可以从$file_return
返回的wp_handle_upload
数组中的“网址”获取该文件名:
$newfilename = basename($file_return["url"]);