LoginSignup
0
0

More than 3 years have passed since last update.

Wordpress REST APIで画像投稿する場合はMIME typeを指定するようになってる

Posted at
post_image.php
function post_image($image){
    $WP_USERNAME = 'user';
    $WP_PASSWORD = 'pw';
    $url = 'http://example.com/wp-json/wp/v2/media';
    $file = $image;

    $data = wp_remote_get($file);

    $image_response = wp_remote_post( $url, array(
    'headers' => array(
        'Authorization' => 'Basic ' . base64_encode($WP_USERNAME.':'.$WP_PASSWORD),
        'Content-Disposition' => 'attachment;filename=' . basename($file),
        'Content-Type' => 'image/jpeg' 
        //ここを指定しないとendpointが403を返す。Wordpress5.4.4まではなくてもいけた
        //mime_content_type()はネットワーク越しだと動かなかったのでとりあえず手打ち
    ),
    'body' => $data["body"]
    ));

    $data = json_decode($image_response['body']);
    $media_id=$data->id;
    return $media_id;   
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0