The delete_metadata() WordPress PHP function is used to delete metadata for a specific object. The type of object can be ‘post’, ‘comment’, ‘term’, ‘user’, or any other object type with an associated meta table.
Usage
Below is a basic example of how to use the function. This example deletes all metadata entries with the key ‘my_meta_key’ for a ‘post’ object with ID 27.
delete_metadata('post', 27, 'my_meta_key');
Parameters
- $meta_type (string – Required): Type of object metadata is for. Accepts ‘post’, ‘comment’, ‘term’, ‘user’, or any other object type with an associated meta table.
- $object_id (int – Required): ID of the object metadata is for.
- $meta_key (string – Required): Metadata key.
- $meta_value (mixed – Optional): Metadata value. Must be serializable if non-scalar. If specified, only delete metadata entries with this value. Otherwise, delete all entries with the specified meta_key. Pass null, false, or an empty string to skip this check. Default: ”
- $delete_all (bool – Optional): If true, delete matching metadata entries for all objects, ignoring the specified object_id. Otherwise, only delete matching metadata entries for the specified object_id. Default: false
More information
See WordPress Developer Resources: delete_metadata()
Be VERY careful when using this function to delete a specific key-value pair. Providing an empty string for $meta_value will cause the check to be skipped entirely, resulting in all keys being deleted!
Examples
Delete Specific Metadata Entry
This example deletes a specific metadata entry for a post with the ID 27, with the key ‘my_meta_key’ and the value ‘my_value’.
$value_to_delete = 'my_value'; if ($value_to_delete != '' && delete_metadata('post', 27, 'my_meta_key', $value_to_delete)) { echo 'The key-value pair was safely deleted'; }
Delete All Metadata Entries for a Specific Key
This example deletes all metadata entries for the ‘post’ object type with the key ‘my_meta_key’, regardless of the object_id.
delete_metadata('post', 0, 'my_meta_key', '', true);
Delete All Metadata Entries for a Specific Object
This example deletes all metadata entries for a ‘post’ object with the ID 27, regardless of the key.
delete_metadata('post', 27, '', '', false);
Delete All Metadata Entries with a Specific Value
This example deletes all metadata entries for the ‘post’ object type with the value ‘my_value’, regardless of the key or object_id.
delete_metadata('post', 0, '', 'my_value', true);
Delete All Metadata Entries
This example deletes all metadata entries for the ‘post’ object type, regardless of the key, value, or object_id.
delete_metadata('post', 0, '', '', true);