// get the file suffix
$suffix = pathinfo($file['name'], PATHINFO_EXTENSION);
// define the save location and filename
$filename = $user_name.'-'.date('YmdHis').'.'.$suffix;
$wp_upload_dir = wp_upload_dir();
$path = $wp_upload_dir['path'].'/'.$filename;
// upload file
if(move_uploaded_file($file['tmp_name'], $path)) {
$attach_id = wp_insert_attachment(array(
'guid' => $wp_upload_dir['url'].'/'.$filename,
'post_mime_type' => $file['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
), $path, get_the_ID());
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $path);
wp_update_attachment_metadata($attach_id, $attach_data);
}
我們可以上傳圖片作爲附件。這樣$ attach_id就是圖片ID。
或者如果有人可以得到上傳圖片的網址? – lizs