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_USERPWD, WP_USER . ':' . WP_PASS);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($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.

1 Answer 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.

post The ID for the associated post of the attachment.

  • Thanks for your reply. But how do I add that parameter to my cURL request? I added the upload function to my question.
    – Tapedeck
    Mar 5, 2021 at 14:14
  • That’s really a curl/PHP question, and not anything to do with WordPress. You’d be better off asking at stackoverflow.com, as such questions are off topic here. Mar 5, 2021 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.