I'm trying to build a WordPress function that takes an image URL, downloads the image, uploads it to the media library, and returns the image ID.
I adapted it from this answer which was taken from here, and I added wp_insert_attachment() at the end.
At the moment it doesn't work because it doesn't return anything or upload any media.
I tired debugging by stepping through with var_dump()
, and I have discovered the $url
parameter is passed in correctly, but nothing is output from download_url
.
Do you know what is wrong?
Can you see anything else in the function that might be broken?
/* Add image to media library from URL and return the new image ID */
function bg_image_upload($url) {
// Gives us access to the download_url() and wp_handle_sideload() functions
require_once( ABSPATH . 'wp-admin/includes/file.php' );
// Download file to temp dir
$timeout_seconds = 10;
$temp_file = download_url( $url, $timeout_seconds );
if ( !is_wp_error( $temp_file ) ) {
// Array based on $_FILE as seen in PHP file uploads
$file = array(
'name' => basename($url), // ex: wp-header-logo.png
'type' => 'image/png',
'tmp_name' => $temp_file,
'error' => 0,
'size' => filesize($temp_file),
);
$overrides = array(
// Tells WordPress to not look for the POST form
// fields that would normally be present as
// we downloaded the file from a remote server, so there
// will be no form fields
// Default is true
'test_form' => false,
// Setting this to false lets WordPress allow empty files, not recommended
// Default is true
'test_size' => true,
);
// Move the temporary file into the uploads directory
$results = wp_handle_sideload( $file, $overrides );
if ( !empty( $results['error'] ) ) {
// Insert any error handling here
} else {
$filename = $results['file']; // Full path to the file
$local_url = $results['url']; // URL to the file in the uploads dir
$type = $results['type']; // MIME type of the file
$wp_upload_dir = wp_upload_dir(); // Get the path to the upload directory.
$attachment = array (
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_mime_type' => $type,
'post_status' => 'inherit',
'post_content' => '',
);
$img_id = wp_insert_attachment( $attachment, $filename );
return $img_id;
}
}
}
PHP Fatal error: Uncaught Error: Call to undefined function wp_generate_password()
but I'm not sure why since I never called that. Here is the full error text: pastebin.com/kf68j5YE – TinyTiger