Using WordPress ‘delete_postmeta’ PHP action

The delete_postmeta WordPress action fires immediately before deleting metadata for a post.

Usage

add_action('delete_postmeta', 'your_custom_function');
function your_custom_function($meta_ids) {
  // your custom code here
}

Parameters

  • $meta_ids (string[]): An array of metadata entry IDs to delete.

More information

See WordPress Developer Resources: delete_postmeta

Examples

Log Deleted Metadata

Log all deleted metadata in a text file.

add_action('delete_postmeta', 'log_deleted_metadata');
function log_deleted_metadata($meta_ids) {
  foreach ($meta_ids as $meta_id) {
    $meta_value = get_metadata_by_mid('post', $meta_id);
    error_log("Deleted metadata - ID: $meta_id, Value: $meta_value->meta_value\n", 3, 'deleted_metadata.log');
  }
}

Prevent Specific Metadata Deletion

Prevent deletion of metadata with a specific key.

add_action('delete_postmeta', 'prevent_specific_meta_deletion');
function prevent_specific_meta_deletion($meta_ids) {
  global $wpdb;
  $meta_key_to_protect = 'protected_meta_key';
  $ids = implode(',', array_map('intval', $meta_ids));
  $wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_id NOT IN ($ids) AND meta_key = '$meta_key_to_protect'");
}

Notify Admin on Metadata Deletion

Send an email to the admin when metadata is deleted.

add_action('delete_postmeta', 'notify_admin_on_meta_deletion');
function notify_admin_on_meta_deletion($meta_ids) {
  $admin_email = get_option('admin_email');
  $subject = 'Metadata Deleted';
  $message = "The following metadata IDs were deleted:\n\n" . implode(", ", $meta_ids);
  wp_mail($admin_email, $subject, $message);
}

Remove Associated Attachment on Metadata Deletion

Delete an attachment when its related metadata is deleted.

add_action('delete_postmeta', 'remove_associated_attachment');
function remove_associated_attachment($meta_ids) {
  foreach ($meta_ids as $meta_id) {
    $meta = get_metadata_by_mid('post', $meta_id);
    if ($meta->meta_key === 'attachment_id') {
      wp_delete_attachment($meta->meta_value, true);
    }
  }
}

Update Cache on Metadata Deletion

Update the cache when post metadata is deleted.

add_action('delete_postmeta', 'update_cache_on_meta_deletion');
function update_cache_on_meta_deletion($meta_ids) {
  foreach ($meta_ids as $meta_id) {
    $meta = get_metadata_by_mid('post', $meta_id);
    $post_id = $meta->post_id;
    clean_post_cache($post_id);
  }
}