Using WordPress ‘media_upload_form_handler()’ PHP function

The media_upload_form_handler WordPress PHP function handles form submissions for the legacy media uploader.

Usage

media_upload_form_handler();

Parameters

This function does not have any parameters.

More information

See WordPress Developer Resources: media_upload_form_handler

This function is part of the legacy media uploader and might be deprecated in future versions. Consider using the newer Media Library for handling media uploads.

Examples

Using media_upload_form_handler with a form

Create a form for media upload and handle the form submission with the media_upload_form_handler function.

HTML code

<!-- HTML Form for uploading media -->
<form enctype="multipart/form-data" method="post">
  <input type="file" name="upload-file" />
  <input type="submit" value="Upload" />
</form>

PHP code

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Call the media_upload_form_handler function to handle the form submission
  media_upload_form_handler();
}

Redirecting after successful media upload

After a successful media upload, redirect the user to a custom URL.

// Call the media_upload_form_handler function
$result = media_upload_form_handler();

// Check if the media was uploaded successfully if (!is_wp_error($result)) { // Redirect to the custom URL wp_redirect('https://example.com/media-upload-success'); exit; }

Displaying error messages after unsuccessful media upload

Show an error message if the media upload fails.

// Call the media_upload_form_handler function
$result = media_upload_form_handler();

// Check if there was an error during the upload if (is_wp_error($result)) { // Display the error message echo '<p>Error: ' . $result->get_error_message() . '</p>'; }

Specifying allowed media types for the uploader

Restrict the media uploader to only allow specific media types (e.g., image files).

HTML code

<!-- HTML Form for uploading media -->
<form enctype="multipart/form-data" method="post">
  <input type="file" name="upload-file" accept="image/*" />
  <input type="submit" value="Upload" />
</form>

PHP code

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Call the media_upload_form_handler function to handle the form submission
  media_upload_form_handler();
}

Adding custom validation for uploaded media

Add custom validation for the uploaded media before using the media_upload_form_handler function.

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Custom validation
  $file = $_FILES['upload-file'];
  $file_size = $file['size'];
  $max_size = 2 * 1024 * 1024; // 2MB

// Check if the file size is within the allowed limit if ($file_size > $max_size) { echo '<p>Error: File size exceeds the allowed limit of 2MB.</p>'; } else { // Call the media_upload_form_handler function to handle the form submission media_upload_form_handler(); } }