In order to upload a file using the wp_remote_post()
function in WordPress, you will need to pass the file as a binary string in the body
argument of the function. Additionally, you will need to set the Content-Type
header to multipart/form-data
and include the file name in the Content-Disposition
header. Here is an example of how you can do this:
$url = 'https://example.com/upload-file'; $file = file_get_contents( '/path/to/file.pdf' ); $headers = array( 'Content-Type' => 'multipart/form-data', 'Content-Disposition' => 'form-data; name="file"; filename="file.pdf"' ); $args = array( 'body' => $file ); $response = wp_remote_post( $url, array( 'headers' => $headers, 'body' => $args )); if ( is_wp_error( $response ) ) { // handle error } else { // handle success }
In the example above, we are reading the binary content of a file using file_get_contents()
and passing it as the body
argument in the wp_remote_post()
function. The Content-Type
and Content-Disposition
headers are set to the appropriate values for file uploads. You can also use libraries like curl or Guzzle to handle this process.
Please note that you need to check the server where the files are going to be uploaded to, if it’s allowed to upload files in that way, also the max file size allowed, and the type of files accepted to avoid any problem.
Last modified: January 13, 2023