-
-
Save tommcfarlin/690a76864cd305dda1b3456faba3fff2 to your computer and use it in GitHub Desktop.
[WordPress] Remote Requests with wp_remote_get
This file contains 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 | |
$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