Random WordPress Function

Learn about a new WordPress function every day!


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 given URL and save it to the uploads directory
$file_url = 'https://example.com/sample-file.zip';
$upload_dir = wp_upload_dir();
$downloaded_file = download_url($file_url, 60); // Set a timeout of 60 seconds
if (is_wp_error($downloaded_file)) {
    echo 'Error downloading file: ' . $downloaded_file->get_error_message();
} else {
    $file_path = $upload_dir['path'] . '/' . basename($file_url);
    rename($downloaded_file, $file_path);
}
// Example 2: Download an image file and set it as the featured image for a post
$image_url = 'https://example.com/image.jpg';
$upload_dir = wp_upload_dir();
$downloaded_image = download_url($image_url);
if (is_wp_error($downloaded_image)) {
    echo 'Error downloading image: ' . $downloaded_image->get_error_message();
} else {
    $file_name = basename($image_url);
    $attachment = array(
        'post_title' => $file_name,
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attachment_id = wp_insert_attachment($attachment, $upload_dir['path'] . '/' . $file_name);
    set_post_thumbnail( $post_id, $attachment_id );
}
// Example 3: Download a CSV file and process its contents
$csv_url = 'https://example.com/data.csv';
$downloaded_csv = download_url($csv_url);
if (is_wp_error($downloaded_csv)) {
    echo 'Error downloading CSV: ' . $downloaded_csv->get_error_message();
} else {
    $csv_file = fopen($downloaded_csv, 'r');
    while (($data = fgetcsv($csv_file)) !== FALSE) {
        // Process CSV data here
    }
    fclose($csv_file);
}