I am able to create a new post by sending a request with cURL against the REST API. That works fine.
I am also able to upload files into the media library with cURL via the REST API. The uploaded files show up properly in the media library just as expected.
But how can I assign those uploaded files to the previously created post without using native WordPress functions, so that they are recognized by the get_attached_media() function in my WordPress theme?
Currently the post is created, the files are uploaded, but they are not attached to the post.
I want to do solve this by using just the REST API and some PHP code without any WordPress functions.
function upload_file_to_wp($filename) {
$file = file_get_contents($filename);
$mime = mime_content_type($filename);
$url = WP_URL . 'media';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $file);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: ' . $mime,
'Content-Disposition: attachment; filename="' . basename($filename) . '"',
]);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, WP_USER . ':' . WP_PASS);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if (defined('WP_DEBUG') && WP_DEBUG !== false) {
error_log('[' . date('Y-m-d H:i:s') . '] cURL result: ' . print_r(json_decode($result, JSON_OBJECT_AS_ARRAY), true) . "n", 3, DEBUG_FILE);
}
}
The WP_URL is the REST API endpoint.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If you look at the documentation for the media endpoint, you’ll see there’s a field, post, that you can use to attach media to a post using its ID.
postThe ID for the associated post of the attachment.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0