[WordPress] Remote Requests with wp_remote_get
<?php | |
$file = wp_remote_get( 'https://example.local/file.png' ); | |
if ( ! isset( $file['headers'] ) ) { | |
/* | |
* TODO: You may want to return early here, display an error, | |
* or provide messaging to the user. | |
*/ | |
} | |
if ( is_wp_error( $file ) ) { | |
/* | |
* TODO: Display an error message to the user that the file they | |
* requested was not successfully retrieved. | |
*/ | |
} | |
/* | |
* Get the base directory where we'll store the file. This will just be | |
* wp-content/uploads. | |
*/ | |
$upload_dir = wp_upload_dir(); | |
$upload_dir = trailingslashit( $upload_dir['basedir'] ); | |
/* | |
* Give the file a name that we'll use to write to disk. And | |
* build the path to the file including the directory and file name. | |
*/ | |
$uploaded_filename = 'uploaded.png'; | |
$file_path = $upload_dir . $uploaded_filename; | |
/* | |
* Open a resource for writing the file, write the data, and then close | |
* the resource. | |
*/ | |
$resource = fopen( $file_path, 'w' ); | |
fwrite( $resource, $file['body'] ); | |
fclose( $resource ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment