使用 json api 在 wordpress 中上传用户图片

Uploade user image in wordpress using json api

我正在使用 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);