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)
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. (For backward compatibility, it is not possible to pass an empty string to delete those entries with an empty string for a value.) Default: ''
$delete_all(true|false)
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
function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
// Make sure meta is added to the post, not a revision.
$the_post = wp_is_post_revision( $post_id );
if ( $the_post ) {
$post_id = $the_post;
}
return delete_metadata( 'post', $post_id, $meta_key, $meta_value );
}
This code shows how to delete all metafields of all posts with the specified key:
$meta_key = 'key_to_delete';
$deleted = delete_metadata( 'post', 0, $meta_key, '', true );
if( $deleted ){
echo "All post meta fields with key $meta_key deleted.";
}
else {
echo "Nothing deleted.";
}
Or use such more descriptive code:
/*
* Remove all post meta data for Custom Post Type (CPT)
* at the time of uninstall of plugin that created this CPT.
* So that plugin do not leave behind any orphan post meta data
* related to its CPT.
*
* You may place this code in uninstall.php file in your plugin root directory.
*/
$meta_type = 'post'; // since we are deleting data for CPT
$object_id = 0; // no need to put id of object since we are deleting all
$meta_key = 'my_meta_key'; // Your target meta_key added using update_post_meta()
$meta_value = ''; // No need to check for value since we are deleting all
$delete_all = true; // This is important to have TRUE to delete all post meta
// This will delete all post meta data having the specified key
delete_metadata( $meta_type, $object_id, $meta_key, $meta_value, $delete_all );
Be VERY careful when using this function to delete a specific key-value pair. As stated, providing an empty string for $meta_value will cause the check to be skipped entirely, resulting in all keys being deleted!
$meta_value …If specified, only delete metadata entries with this value. Otherwise, delete all entries with the specified meta_key…
To avoid accidentally deleting ALL key instances, use a short-circuit check:
$value_to_delete = get_value(); // may return empty string
if ( $value_to_delete && delete_metadata( 'post', 27, 'key', $value_to_delete ) ) {
// the key-value pair was safely deleted
}