The delete_{$meta_type}_meta WordPress PHP action fires immediately before deleting metadata of a specific type.
Usage
add_action('delete_post_meta', 'your_custom_function', 10, 4);
function your_custom_function($meta_ids, $object_id, $meta_key, $_meta_value) {
// your custom code here
return $meta_ids;
}
Parameters
- $meta_ids (string[]): An array of metadata entry IDs to delete.
- $object_id (int): ID of the object metadata is for.
- $meta_key (string): Metadata key.
- $_meta_value (mixed): Metadata value.
More information
See WordPress Developer Resources: delete_{$meta_type}_meta
Examples
Log metadata deletion for posts
Log each time a post’s metadata is deleted.
add_action('delete_post_meta', 'log_post_meta_deletion', 10, 4);
function log_post_meta_deletion($meta_ids, $object_id, $meta_key, $_meta_value) {
error_log("Post meta deleted: object_id - {$object_id}, meta_key - {$meta_key}");
return $meta_ids;
}
Prevent deletion of specific metadata for users
Prevent deletion of the ‘custom_field’ metadata for users.
add_action('delete_user_meta', 'prevent_custom_field_deletion', 10, 4);
function prevent_custom_field_deletion($meta_ids, $object_id, $meta_key, $_meta_value) {
if ($meta_key === 'custom_field') {
return false;
}
return $meta_ids;
}
Delete related metadata when a term’s metadata is deleted
When a term’s ‘main_image’ metadata is deleted, also delete the ‘thumbnail_image’ metadata.
add_action('delete_term_meta', 'delete_related_term_meta', 10, 4);
function delete_related_term_meta($meta_ids, $object_id, $meta_key, $_meta_value) {
if ($meta_key === 'main_image') {
delete_term_meta($object_id, 'thumbnail_image');
}
return $meta_ids;
}
Notify admin when comment metadata is deleted
Send a notification to the admin when a comment’s ‘custom_flag’ metadata is deleted.
add_action('delete_comment_meta', 'notify_admin_on_custom_flag_removal', 10, 4);
function notify_admin_on_custom_flag_removal($meta_ids, $object_id, $meta_key, $_meta_value) {
if ($meta_key === 'custom_flag') {
$admin_email = get_option('admin_email');
wp_mail($admin_email, 'Custom Flag Removed', 'The custom flag has been removed from comment ID: ' . $object_id);
}
return $meta_ids;
}
Clear cache when post metadata is deleted
Clear the cache for a post when its metadata is deleted.
add_action('delete_post_meta', 'clear_post_cache_on_meta_deletion', 10, 4);
function clear_post_cache_on_meta_deletion($meta_ids, $object_id, $meta_key, $_meta_value) {
wp_cache_delete($object_id, 'posts');
return $meta_ids;
}