Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bionary's avatar

Create Media via WordPress API

I'm attempting to add media to a remote WordPress site of mine. I am able to CRUD posts and categories just fine. I'm finding it impossible to create images (media) however. My Code looks like this:

    $file = 'horizontal sample.jpg';
    $img = Storage::disk('shared')->get('/samples/'.$file);
    $mimetype = 'image/jpeg';

    $formData =[
        'alt_text' => 'my alt',
        'caption' => 'the caption',
        'description' => 'the description',
    ];
    $headers = [
       // 'cache-control' => 'no-cache',
        'Content-Type' => $mimetype,
        'Content-Disposition' => "attachment; filename=$file",
        //'accept' => 'application/json'
    ];

    $response = Http
        ::withBasicAuth($this->username, $this->password)
        ->asForm()
        ->asMultipart()
        ->withHeaders($headers)
        ->attach('attachment', $img, null, ['Content-Type' => $mimetype])
        ->post($this->baseUrl . "/wp/v2/media", $formData);

    $remoteResponseElems =  collect($response->json());
    dd($remoteResponseElems);

The code above creates a media entry but the image file is not created correctly...it's corrupted or something. They show up as blank images in the WordPress media library. When using FTP and looking at the "uploaded" files they are corrupted. The filenames are there but they cannot be opened.

Full disclosure, I am fully aware of: https://developer.wordpress.org/rest-api/reference/media/#create-a-media-item

..along with the dozens of stack overflow examples "claiming" they can add a media item. I've tried them all, one at a time over the past few days and none of them work. (so please don't link to something if you are not using the code successfully yourself)

Yes WordPress is crap, but I really need to enable this functionality.

Has anyone successfully added media to WordPress remotely via their API?

0 likes
0 replies

Please or to participate in this conversation.