Function Signature:
download_url
Function Description:
Downloads a URL to a local temporary file using the WordPress HTTP API.
Function Examples:
⚠️ Examples below are generated with GPT-3 once every hour. Do not take them too seriously.
Consider them as some extra input in your learning process - reason about them. Will it work? What could fail?
// Example 1: Download a file from a URL and save it to the uploads directory
$url = 'https://example.com/file.zip';
$downloaded_file = download_url( $url );
if( is_wp_error( $downloaded_file ) ){
// Handle the error here
} else {
$file_path = $downloaded_file;
$file_name = basename( $url );
$file_type = wp_check_filetype( $file_name, null );
$attachment = array(
'post_title' => $file_name,
'post_mime_type' => $file_type['type']
);
$attachment_id = wp_insert_attachment( $attachment, $file_path );
// Further processing of the downloaded file
}
// Example 2: Download a file from a URL and delete it after processing
$url = 'https://example.com/image.jpg';
$downloaded_file = download_url( $url );
if( is_wp_error( $downloaded_file ) ){
// Handle the error here
} else {
// Process the downloaded file
// Delete the downloaded file after processing
unlink( $downloaded_file );
}
// Example 3: Download a file from a URL and display it in a WordPress post
$url = 'https://example.com/document.pdf';
$downloaded_file = download_url( $url );
if( is_wp_error( $downloaded_file ) ){
// Handle the error here
} else {
$file_path = $downloaded_file;
$file_name = basename( $url );
$file_type = wp_check_filetype( $file_name, null );
$attachment = array(
'post_title' => $file_name,
'post_mime_type' => $file_type['type']
);
$attachment_id = wp_insert_attachment( $attachment, $file_path );
// Display the downloaded file in a WordPress post
echo wp_get_attachment_link( $attachment_id );
}