Creating a new attachment via the POST /wp/v2/media
endpoint can be done in two ways:
Set the Content-Disposition
header to attachment; filename=<file name>
and the Content-Type
header to the correct MIME type such as image/jpeg
, and then set the request body to the binary file content.
Set the Content-Type
header to multipart/form-data; boundary=<boundary>
and then set the request body to the multi-part data like you can see here which begins with ---------------------------<boundary>
and ends with ---------------------------<boundary>--
.
And in specific to WordPress, the advantage of using this option is that you can set custom attachment post data like the post title and slug. But make sure the form data name for the media file is exactly file
— and not filedata
, file_content
or something else.
And in R, you could easily do the above like so with the Authorization
header set to Bearer <token>
, and that we're uploading a JPEG image:
Example based on the option 1 above
r <- POST(
'https://example.com/wp-json/wp/v2/media',
add_headers(
'Authorization' = paste('Bearer', token, sep = ' '),
'Content-Disposition' = 'attachment; filename="test-using-R-4.0.4.jpg"',
'Content-Type' = 'image/jpeg'
),
body = upload_file('test.jpg', 'image/jpeg')
)
d <- content(r)
cat( ifelse(! is.null(d[['id']]),
paste('success - id:', d['id']),
paste('error:', d['message']))
)
Example based on the option 2 above
r <- POST(
'https://example.com/wp-json/wp/v2/media',
add_headers(
'Authorization' = paste('Bearer', token, sep = ' '),
),
body = list(
file = upload_file('test.jpg', 'image/jpeg'),
title = 'custom title',
slug = 'custom-slug'
)
)
d <- content(r)
cat( ifelse(! is.null(d[['id']]),
paste('success - id:', d['id']),
paste('error:', d['message']))
)
And if you're using the default Application Password feature introduced in WordPress 5.6, then you would want to use authenticate()
instead of the add_headers()
in Option 2 above:
# Replace this:
add_headers(
'Authorization' = paste('Bearer', token, sep = ' '),
),
# with this one:
authenticate('<your WordPress username>', '<your WordPress Application Password>'),
So I hope the examples, which were tried & tested working with R-4.0.4, also work for you.