Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top