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/wp-content/uploads/file.zip';
$upload_dir = wp_upload_dir();
$downloaded_file = download_url( $file_url, 300 );
if( is_wp_error( $downloaded_file ) ){
    // Handle error
} else {
    $file_name = basename( $file_url );
    $file_path = $upload_dir['path'] . '/' . $file_name;
    rename( $downloaded_file, $file_path );
}
// Example 2: Download an image from a remote URL and set it as the featured image of a post
$image_url = 'https://example.com/image.jpg';
$post_id = 123;
$upload_dir = wp_upload_dir();
$downloaded_image = download_url( $image_url, 60 );
if( ! is_wp_error( $downloaded_image ) ){
    $file_name = basename( $image_url );
    $file_path = $upload_dir['path'] . '/' . $file_name;
    $attachment_id = media_handle_sideload( array( 'file' => $file_path, 'post_id' => $post_id ) );
    if( is_wp_error( $attachment_id ) ){
        // Handle error
    } else {
        set_post_thumbnail( $post_id, $attachment_id );
    }
}
// Example 3: Download a CSV file from a remote URL and process its contents
$csv_url = 'https://example.com/data.csv';
$downloaded_csv = download_url( $csv_url, 120 );
if( ! is_wp_error( $downloaded_csv ) ){
    $csv_data = file_get_contents( $downloaded_csv );
    $csv_rows = str_getcsv( $csv_data, "\n" );
    foreach( $csv_rows as $row ){
        $csv_columns = str_getcsv( $row );
        // Process each row of the CSV file
    }
} else {
    // Handle error
}