Using WordPress ‘async_upload_{$type}’ PHP filter

The async_upload_{$type} WordPress PHP filter allows you to modify the returned ID of an uploaded attachment based on its type.

Usage

add_filter('async_upload_{$type}', 'your_custom_function', 10, 1);

function your_custom_function($id) {
  // your custom code here
  return $id;
}

Parameters

  • $type (string) – The attachment type, such as ‘audio’, ‘file’, ‘image’, or ‘video’.
  • $id (int) – The uploaded attachment ID.

More information

See WordPress Developer Resources: async_upload_{$type}

Examples

Change Image Attachment ID

Modify the ID of an uploaded image attachment.

add_filter('async_upload_image', 'change_image_attachment_id', 10, 1);

function change_image_attachment_id($id) {
  // Modify the image attachment ID
  $new_id = $id * 2;
  return $new_id;
}

Add Custom Metadata to Audio Attachment

Add custom metadata to an uploaded audio attachment.

add_filter('async_upload_audio', 'add_custom_metadata_to_audio', 10, 1);

function add_custom_metadata_to_audio($id) {
  // Add custom metadata to the audio attachment
  update_post_meta($id, 'custom_metadata', 'your_custom_value');
  return $id;
}

Log Video Attachment Upload

Log the uploaded video attachment ID to a file.

add_filter('async_upload_video', 'log_video_upload', 10, 1);

function log_video_upload($id) {
  // Log the video attachment ID to a file
  error_log("Uploaded video attachment ID: " . $id, 3, "uploads.log");
  return $id;
}

Send Email Notification for File Upload

Send an email notification when a file is uploaded.

add_filter('async_upload_file', 'send_email_on_file_upload', 10, 1);

function send_email_on_file_upload($id) {
  // Send email notification for uploaded file
  $email_subject = "A new file has been uploaded";
  $email_body = "File attachment ID: " . $id;
  wp_mail('[email protected]', $email_subject, $email_body);
  return $id;
}

Delete Uploaded Image If Too Large

Delete an image attachment if its dimensions exceed the allowed size.

add_filter('async_upload_image', 'delete_large_images', 10, 1);

function delete_large_images($id) {
  // Check the image dimensions
  $max_width = 2000;
  $max_height = 2000;
  $image_data = wp_get_attachment_metadata($id);

  if ($image_data['width'] > $max_width || $image_data['height'] > $max_height) {
    // Delete the image if it's too large
    wp_delete_attachment($id, true);
    return null;
  }

  return $id;
}