// 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