我正在使用WordPress数据库开发移动应用程序。我使用JSON API创建了一个用户并更改了用户详细信息。但我不知道如何使用API将用户图像从手机上传到WordPress数据库。谁能帮我吗?
试试这个代码。我正在使用此代码在API中上传用户个人资料图片
你必须在移动设备中将图像转换为base64_encode并发送给API
<?php
$password = esc_attr( $password );
$random_password = wp_generate_password( 12, false );
$email = sanitize_email( $useremail );
$first_name = sanitize_text_field( $firstname );
$phoneno = sanitize_text_field( $phoneno );
$type = sanitize_text_field( $type );
$imgdata = base64_decode($data["avatar"]);
$userdata = array(
'user_login' => $email,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
'user_nicename' => $first_name,
'first_name' => $first_name,
'last_name' => '',
);
$new_user = wp_insert_user ( $userdata );
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$type_file = explode('/', $mime_type);
$avatar = time() . '.' . $type_file[1];
$uploaddir = wp_upload_dir();
$myDirPath = $uploaddir["path"];
$myDirUrl = $uploaddir["url"];
file_put_contents($uploaddir["path"].'/'.$avatar,$imgdata);
$filename = $myDirUrl.'/'.basename( $avatar );
$wp_filetype = wp_check_filetype(basename($filename), null );
$uploadfile = $uploaddir["path"] .'/'. basename( $filename );
$attachment = array(
"post_mime_type" => $wp_filetype["type"],
"post_title" => preg_replace("/\.[^.]+$/", "" , basename( $filename )),
"post_content" => "",
"post_status" => "inherit",
'guid' => $uploadfile,
);
require_once(ABSPATH . '/wp-load.php');
require_once(ABSPATH . 'wp-admin' . '/includes/file.php');
require_once(ABSPATH . 'wp-admin' . '/includes/image.php');
$attachment_id = wp_insert_attachment( $attachment, $uploadfile );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploadfile );
wp_update_attachment_metadata( $attachment_id, $attach_data );
update_post_meta($attachment_id,'_wp_attachment_wp_user_avatar',$new_user);
update_user_meta($new_user, 'wp_user_avatar', $attachment_id);