Forked from petenelson/wp-multipart-image-upload.php
Last active
May 2, 2025 03:53
-
-
Save benlk/c1de8fdfc5c38b4a5a1a2e49c844b0a2 to your computer and use it in GitHub Desktop.
WordPress: Upload image to REST API via multipart/form-data body
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Creates a multipart/form-data body for an HTML file and some form fields. | |
* | |
* @link https://gist.github.com/petenelson/828a1fdb390973aedebe0396abc31234 | |
* @param string $file_contents The file contents | |
* @param array $fields The form fields. | |
* @return array The boundary ID and the body. | |
*/ | |
function create_multipart_form_data( string $file_contents, array $fields = [] ): array { | |
$boundary = wp_generate_password( 24, false, false ); | |
$body = '--' . $boundary . "\r\n"; | |
foreach ( $fields as $name => $value ) { | |
// Such as the "meta" field for post meta. | |
if ( is_array( $value ) ) { | |
foreach ( $value as $sub_name => $sub_value ) { | |
$body .= 'Content-Disposition: form-data; name="' . $name . '[' . $sub_name . ']"' . "\r\n\r\n"; | |
$body .= $sub_value . "\r\n"; | |
} | |
} else { | |
$body .= 'Content-Disposition: form-data; name="' . $name . '"' . "\r\n\r\n"; | |
$body .= $value . "\r\n"; | |
} | |
$body .= '--' . $boundary . "\r\n"; | |
} | |
$body .= 'Content-Disposition: form-data; name="file"; filename="' . 'file.html' . '"' . "\r\n"; | |
// this is hardcoded because we know we're doing HTML here. | |
$body .= 'Content-Type: text/html; charset=utf-8' . "\r\n\r\n"; | |
$body .= $file_contents . "\r\n"; | |
$body .= '--' . $boundary . '--'; | |
return [ | |
'boundary' => $boundary, | |
'body' => $body, | |
]; | |
} | |
// Example code. | |
// Post meta can be sent in the "meta" field, but it needs to be registered via | |
// register_post_meta(), see example. | |
$form_fields = [ | |
'post_title' => 'Image title', | |
'post_name' => 'custom-slug', | |
'meta' => [ | |
'test_hello' => 'world', | |
], | |
]; | |
$multipart = create_multipart_form_data( $image_filename, $filename, $form_fields ); | |
$headers['Content-Type'] = 'multipart/form-data; boundary=' . $multipart['boundary']; | |
$args = [ | |
'headers' => $headers, | |
'body' => $multipart['body'], | |
'sslverify' => false, | |
'timeout' => 30, | |
]; | |
$response = wp_remote_post( $image_upload_endpoint, $args ); | |
// Example of register_post_meta(). | |
// register_post_meta( | |
// 'attachment', | |
// 'test_hello', [ | |
// 'type' => 'string', | |
// 'description' => 'Test meta field.', | |
// 'single' => true, | |
// 'show_in_rest' => [ | |
// 'schema' => [ | |
// 'type' => 'string', | |
// ], | |
// ], | |
// ] | |
// ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment