The delete_{$meta_type}_metadata WordPress PHP filter short-circuits deleting metadata of a specific type. The dynamic part of the filter name, $meta_type, refers to the meta object type (post, comment, term, user, or any other type with an associated meta table).
Usage
add_filter('delete_post_metadata', 'your_custom_function', 10, 5); function your_custom_function($delete, $object_id, $meta_key, $meta_value, $delete_all) { // Your custom code here return $delete; }
Parameters
- $delete: null|bool – Whether to allow metadata deletion of the given type.
- $object_id: int – ID of the object metadata is for.
- $meta_key: string – Metadata key.
- $meta_value: mixed – Metadata value. Must be serializable if non-scalar.
- $delete_all: bool – Whether to delete the matching metadata entries for all objects, ignoring the specified $object_id. Default false.
More information
See WordPress Developer Resources: delete_{$meta_type}_metadata
Examples
Prevent Deletion of Specific Post Metadata
Prevent deleting a specific post metadata with the key “important_key”:
add_filter('delete_post_metadata', 'prevent_important_key_deletion', 10, 5); function prevent_important_key_deletion($delete, $object_id, $meta_key, $meta_value, $delete_all) { if ($meta_key == 'important_key') { return false; } return $delete; }
Only Allow Deletion of User Metadata if Admin
Only allow deletion of user metadata if the current user is an administrator:
add_filter('delete_user_metadata', 'only_admin_delete_user_metadata', 10, 5); function only_admin_delete_user_metadata($delete, $object_id, $meta_key, $meta_value, $delete_all) { if (current_user_can('manage_options')) { return $delete; } return false; }
Prevent Deletion of All Metadata Entries
Prevent deletion of all metadata entries when $delete_all is set to true:
add_filter('delete_post_metadata', 'prevent_delete_all_metadata', 10, 5); function prevent_delete_all_metadata($delete, $object_id, $meta_key, $meta_value, $delete_all) { if ($delete_all) { return false; } return $delete; }
Log Deleted Metadata
Log the metadata that has been deleted to a custom table:
add_filter('delete_post_metadata', 'log_deleted_metadata', 10, 5); function log_deleted_metadata($delete, $object_id, $meta_key, $meta_value, $delete_all) { // Log deleted metadata to custom table // ... return $delete; }
Only Delete Metadata with a Specific Value
Only delete metadata if it has a specific value, for example “to_be_deleted”:
add_filter('delete_post_metadata', 'only_delete_specific_value', 10, 5); function only_delete_specific_value($delete, $object_id, $meta_key, $meta_value, $delete_all) { if ($meta_value == 'to_be_deleted') { return $delete; } return false; }