【问题标题】:Uploade user image in wordpress using json api使用 json api 在 wordpress 中上传用户图像
【发布时间】:2018-01-05 05:29:45
【问题描述】:

我正在使用 WordPress 数据库开发移动应用程序。我使用 JSON API 创建了一个用户并更改了用户详细信息。但我不知道如何使用 API 将用户图像从移动设备上传到 WordPress 数据库。谁能帮帮我?

【问题讨论】:

    标签: wordpress wordpress-rest-api


    【解决方案1】:

    试试这个代码。我正在使用此代码在 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);
    

    【讨论】:

      猜你喜欢
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2019-01-23
      • 2022-01-25
      • 2023-02-11
      • 1970-01-01
      • 2018-05-19
      相关资源
      最近更新 更多