| 1 | <?php
|
|---|
| 2 |
|
|---|
| 3 | require_once( '../../../../wp-config.php' );
|
|---|
| 4 |
|
|---|
| 5 | function endl(): string {
|
|---|
| 6 | return "\r\n";
|
|---|
| 7 | }
|
|---|
| 8 |
|
|---|
| 9 | $file = __DIR__ . '/dummy_file.png';
|
|---|
| 10 | $filename = basename( $file );
|
|---|
| 11 | $filetype = filetype( $file );
|
|---|
| 12 |
|
|---|
| 13 | $path = 'http://your.wordpress.tldde/wp-json/wp/v2/media';
|
|---|
| 14 |
|
|---|
| 15 |
|
|---|
| 16 | $boundary = wp_generate_password( 10 );
|
|---|
| 17 | $headers = array(
|
|---|
| 18 | 'content-type' => 'multipart/form-data; boundary=' . $boundary
|
|---|
| 19 | );
|
|---|
| 20 |
|
|---|
| 21 |
|
|---|
| 22 | $payload = '';
|
|---|
| 23 | // First, add the standard POST fields:
|
|---|
| 24 | $post_fields = [
|
|---|
| 25 | 'title' => 'test' . $i . '_' . time(),
|
|---|
| 26 | ];
|
|---|
| 27 | foreach ( $post_fields as $name => $value ) {
|
|---|
| 28 | $payload .= '--' . $boundary . endl();
|
|---|
| 29 | $payload .= 'Content-Disposition: form-data; name="' . $name . '"' . endl() . endl();
|
|---|
| 30 | $payload .= $value . endl();
|
|---|
| 31 | }
|
|---|
| 32 |
|
|---|
| 33 | $payload .= '--' . $boundary . endl();
|
|---|
| 34 | $payload .= 'Content-Disposition: form-data; name="meta[my_meta]"' . endl() . endl();
|
|---|
| 35 | $payload .= '1' . endl();
|
|---|
| 36 |
|
|---|
| 37 | $payload .= '--' . $boundary . endl();
|
|---|
| 38 | $payload .= 'Content-Disposition: form-data; name="file"; filename="' . $filename . '"' . endl();
|
|---|
| 39 | $payload .= 'Content-Type: ' . $filetype . endl() . endl();
|
|---|
| 40 | $payload .= file_get_contents( $file ) . endl();
|
|---|
| 41 | $payload .= '--' . $boundary . '--';
|
|---|
| 42 |
|
|---|
| 43 |
|
|---|
| 44 | $request = [
|
|---|
| 45 | 'headers' => $headers,
|
|---|
| 46 | 'body' => $payload,
|
|---|
| 47 | ];
|
|---|
| 48 | $response = wp_remote_post( $path, $request );
|
|---|
| 49 | //var_dump( json_decode( wp_remote_retrieve_body( $response ) ) );
|
|---|
| 50 | //var_dump( $response );
|
|---|
| 51 | echo $response['body'];
|
|---|