Add media with WP-Rest-API v2

SO! This is fun.

Keep in mind the WP-API is still very, very much a work-in-progress.

Content-Disposition

I found an issue reported on the WP-API issue queue about Content-Disposition. This is a required header for posting new media content and there are some very, very strict requirements when it comes to providing this in the proper format.

The Purpose of Create Media Endpoint

First, Let’s take a step back. The API assumes at this point you have already uploaded a new file to the correct directory. This endpoint is creating the media content in the database that references this file.

The solution

You have to specify the filename of the media file to associate to your new content. This cannot be a remote url. As you can see from the v2 documentation, source_url and link are read-only. All you have to do to successfully submit your new content is add the following to your header:

'Content-Disposition' => 'filename=name-of-file.jpg',

As mentioned in the ticket, you cannot add quotes or specify the method you’re using to send the file. It must be in the format above. At least, this is the case until they change it all around.

Make sure the file type is one of the accepted file types and you’re including the extension of the file is included in the request. Thanks to Dr Deo in the comments.

For the record, I laughed with giddy joy when I finally figured this one out… scared the hell out of my wife.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)