Using WordPress ‘attachment_updated’ PHP action

The attachment_updated WordPress PHP action is triggered when an existing attachment is updated.

Usage

add_action('attachment_updated', 'your_custom_function', 10, 3);

function your_custom_function($post_id, $post_after, $post_before) {
  // your custom code here
}

Parameters

  • $post_id (int): The ID of the attachment post.
  • $post_after (WP_Post): The post object after the update.
  • $post_before (WP_Post): The post object before the update.

More information

See WordPress Developer Resources: attachment_updated

Examples

Log attachment updates

Log attachment updates to a custom log file.

add_action('attachment_updated', 'log_attachment_updates', 10, 3);

function log_attachment_updates($post_id, $post_after, $post_before) {
  $log_message = sprintf(
    'Attachment ID %d updated from %s to %s',
    $post_id,
    $post_before->post_title,
    $post_after->post_title
  );
  error_log($log_message, 3, '/path/to/your/custom/log/file.log');
}

Send email notifications on attachment updates

Send an email notification to the site admin when an attachment is updated.

add_action('attachment_updated', 'email_on_attachment_update', 10, 3);

function email_on_attachment_update($post_id, $post_after, $post_before) {
  $subject = 'Attachment Updated';
  $message = sprintf(
    'Attachment ID %d has been updated from %s to %s.',
    $post_id,
    $post_before->post_title,
    $post_after->post_title
  );
  wp_mail(get_option('admin_email'), $subject, $message);
}

Update a custom field on attachment update

Update a custom field when an attachment is updated.

add_action('attachment_updated', 'update_custom_field_on_attachment_update', 10, 3);

function update_custom_field_on_attachment_update($post_id, $post_after, $post_before) {
  update_post_meta($post_id, 'your_custom_field_key', 'your_custom_value');
}

Change the attachment’s author when the title is updated

Update the attachment’s author when the title is changed.

add_action('attachment_updated', 'change_author_on_title_update', 10, 3);

function change_author_on_title_update($post_id, $post_after, $post_before) {
  if ($post_before->post_title != $post_after->post_title) {
    wp_update_post([
      'ID' => $post_id,
      'post_author' => 'new_author_id'
    ]);
  }
}

Delete a transient when an attachment is updated

Remove a transient when an attachment is updated to refresh cached data.

add_action('attachment_updated', 'delete_transient_on_attachment_update', 10, 3);

function delete_transient_on_attachment_update($post_id, $post_after, $post_before) {
  delete_transient('your_transient_key');
}