Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created January 10, 2017 15:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/690a76864cd305dda1b3456faba3fff2 to your computer and use it in GitHub Desktop.
Save tommcfarlin/690a76864cd305dda1b3456faba3fff2 to your computer and use it in GitHub Desktop.
[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