Managing Media Library Uploads with wp_handle_upload
The WordPress media library is a friendly screen for humans: drag a file in, watch the progress bar, tick the boxes. Plenty of sites never need anything else. Trouble starts when files arrive without a human attached to them — a migration script pulling thousands of legacy images off a closed platform, a headless front end that uploads receipts from a point-of-sale terminal, an importer that fetches supplier product photography every night. In those situations you want the same behaviour the media uploader uses, without the browser.
wp_handle_upload() is the function behind the admin uploader. Give it a file array shaped like an entry from $_FILES and it will validate the upload, work out a safe filename, move the file into the uploads directory and hand back an array describing where everything landed. The catch, and the source of most support tickets, is that it stops there. It stores the file on disk; it does not create the attachment post that makes the file appear in the media library.
Getting those two halves to talk is the whole craft. A stored file with no attachment record is invisible in the admin, gets swept up by cleanup routines, and never gets a thumbnail. An attachment record pointing at a file that was never moved is worse: a broken image in a product grid and a 404 for a customer. Australian retailers running WooCommerce hit this constantly when a nightly feed replaces product photography.
Before writing any code, know what the environment gives you. The uploads directory needs to be writable by the web server user, PHP needs permission to write to it, and your host may run Nginx rather than Apache, which changes how you lock that directory down. If your site stores client documents — tax returns, enrolment forms, site photos with street addresses on them — you are handling personal information under the Privacy Act 1988 and the Australian Privacy Principles, which puts the storage location and access rules in the brief rather than in a footnote.
How wp_handle_upload Processes a File
The signature is short: wp_handle_upload( array &$file, $overrides = false, $time = null ). The first argument is passed by reference because the function rewrites parts of it, including the corrected filename and the final path. The second is an array of overrides, and the third lets you place the file into a year-and-month folder structure by passing a timestamp. The function lives in wp-admin/includes/file.php, so a front-end script or WP-CLI task should load that file first.
Internally the sequence is predictable. The error code in the array is checked before anything else, so UPLOAD_ERR_INI_SIZE or UPLOAD_ERR_PARTIAL fails early with a WP_Error rather than a half-finished move. Next comes the type check: WordPress compares the extension against the allowed mime list, then uses fileinfo to inspect the actual bytes, so a renamed executable will not slip through as a JPEG. The type key in your array is largely decorative — trust the extension and the file signature, not what the browser claimed.
Once validation passes, the filename is made unique with wp_unique_filename(), the file moves into the uploads directory, and the return array contains file, url, type and subdir. When something goes wrong you get a WP_Error whose code might be upload_err, invalid_filetype or test_form. Checking the return with is_wp_error() before touching $upload['file'] is the single most important line in the whole snippet.
Assembling the File Array Correctly
Most integrations start from $_FILES. Take the entry, rename the keys to what WordPress expects if you need to, and set error to UPLOAD_ERR_OK when you know the transfer succeeded. The array usually needs name, type, tmp_name, error and optionally size. The function reads the temporary path from tmp_name and never inspects the size key itself, so populate that value if you want your own size ceiling to run before the call rather than after.
When the file did not arrive through an HTTP request — a PDF you generated on the server, an image pulled from an FTP archive — you want wp_handle_sideload() instead. The sideload variant expects a path already on disk, copies rather than moves the file, and skips the upload-form checks. It is the right tool for migration scripts and for the nightly job a Brisbane wholesaler runs to refresh catalogue photography from a supplier feed.
Security is the part worth getting right. Check current_user_can( 'upload_files' ) before accepting anything from a logged-in user, and verify a nonce on any front-end form you build. For genuine uploads, is_uploaded_file() confirms the path came through PHP's upload handling, which blocks a common trick where an attacker tries to trick your code into reading a system file. Set test_form to false in your overrides for programmatic calls. That check applies to HTTP uploads only; sideloaded files need your own path validation, including confirming the path sits inside a directory your code owns.
Controlling Names, Types, and Destinations
The overrides array is where you shape the outcome. mimes restricts which types are accepted, upload_path and upload_url_path place the file in a subfolder of the uploads directory, unique_filename_callback swaps in your own naming logic, and upload_error_handler changes the message returned when validation fails. Filtered alternatives exist for most of these: wp_handle_upload_prefilter, wp_handle_upload_overrides, upload_mimes, upload_dir and wp_check_filetype_and_ext all adjust behaviour without rewriting the function.
Filenames need thought on Australian sites. Dates should read dd/mm/yyyy to match the convention your clients expect, and a photo named Site Photo — 2026-10-28.jpg should survive sanitisation intact. wp_unique_filename() appends a numeric suffix when a name already exists, so the URL stays stable instead of overwriting a customer's earlier upload. For a document library where you want deterministic names, set unique_filename to false and handle collisions yourself.
Two practical hazards deserve attention. First, the uploads directory should never execute PHP: an Apache site can drop an .htaccess file there, while an Nginx host needs a matching location block that returns a 404 for .php requests inside that folder. Second, modern phones produce HEIC and large camera formats by default, and fileinfo on a lean server may not recognise them, producing an invalid_filetype error for a perfectly legitimate photo taken on a tradie's phone outside a Melbourne job site. Accepting those formats means extending the allowed mime list and confirming your image stack can process them.
Turning Files into Media Library Records
Once the file is stored, create the attachment. wp_insert_attachment() takes the post fields as an array along with the file path and the parent post ID, then wp_generate_attachment_metadata( $attachment_id, $file ) builds thumbnail and size metadata for images, and wp_update_attachment_metadata() writes it back. Set the file as a featured image with set_post_thumbnail( $post_id, $attachment_id ), which also attaches the attachment to the post so the relationship shows in the editor.
Non-image files skip the metadata generator. For a PDF invoice or a CSV export, set the mime type and a minimal _wp_attachment_metadata array instead, because wp_generate_attachment_metadata() will do nothing useful for them. Titles, captions and alt text are ordinary fields on the attachment post, so update them in the same pass and your accessibility checks stay satisfied.
If uploads become a browsable resource library — quotes, photo galleries, downloadable guides — the surrounding theme matters as much as the function calls. The walkthrough on breadcrumbs without a plugin shows how to signal where an uploaded file sits in the site hierarchy, and it pairs neatly with the attachment's post_parent value.
Sideloading, Bulk Runs, and Failure Recovery
Batch work needs different tactics from single uploads. Loop over your files, call the handler one at a time, and log every failure with its error code; a run of two thousand images will hit at least one bad file, and one unhandled WP_Error aborting the whole job is a familiar Friday afternoon problem. On a modest host, a few hundred files per request is a realistic ceiling, while WP-CLI's wp media import handles far larger batches with a much lighter footprint.
Long-running jobs fit naturally into WordPress cron or Action Scheduler, letting you resume where you stopped and record progress in an option or a dedicated table. Keep timezones in mind: sites in Sydney, Melbourne and Brisbane share AEST or AEDT, Perth runs on AWST, Adelaide and Darwin on ACST and Hobart on AEST, so a job set for midnight lands at different wall-clock times across the country. Storing timestamps in UTC avoids the confusion when a customer complains that their receipt appeared a day early.
Australian deployments add constraints worth designing for. Keeping the site and its uploads in an onshore region — Sydney or Melbourne hosting is common for businesses that want data held in Australia — simplifies the compliance story under the Privacy Act 1988 and the Notifiable Data Breaches scheme. WooCommerce sites also depend on accurate product imagery to describe goods under the Australian Consumer Law, so a failed image import carries legal weight rather than being purely cosmetic. If the importer also sends email, the Spam Act 2003 governs that side of the workflow, and the local WordPress community remains active with regular meetups in Sydney and Melbourne where these patterns get compared and refined.