Using WordPress ‘delete_user_meta()’ PHP function

The delete_user_meta() WordPress PHP function is used to remove metadata from a user based on specific criteria. This function can match and remove metadata based on the key, or key and value. If you remove data based on key and value, it ensures that duplicate metadata with the same key is not removed. It also allows removing all metadata matching a specific key, if needed.

Usage

Here’s a simple example of how the function can be used:

if ( ! delete_user_meta( $user_id, '_province' ) ) {
  echo "Oops! Error while deleting this information!";
}

In this example, the function tries to delete the metadata with the key ‘_province’ from the user with the ID stored in $user_id. If the function fails, it prints an error message.

Parameters

  • $user_id (int, required): The ID of the user from whom the metadata should be removed.
  • $meta_key (string, required): The name of the metadata to be removed.
  • $meta_value (mixed, optional): The value of the metadata. If provided, only rows that match the value will be removed. This value must be serializable if it’s not a scalar type. The default value is an empty string.

More information

See WordPress Developer Resources: delete_user_meta()

This function is a part of WordPress core and is not deprecated as of the time of writing. For more information, you can check the source code in the file wp-includes/user.php.

Examples

Deleting User Meta Data

In this example, we are trying to delete the user’s location data.

if ( ! delete_user_meta( $user_id, 'location' ) ) {
  echo "Error while deleting location data!";
}

Deleting Specific Meta Data

Here, we’re removing a user’s phone number only if it matches a specific value.

if ( ! delete_user_meta( $user_id, 'phone_number', '123-456-7890' ) ) {
  echo "Error while deleting phone number!";
}

Deleting Multiple Values

This example removes all instances of ‘favorite_color’ being ‘blue’ from a user’s metadata.

while( delete_user_meta( $user_id, 'favorite_color', 'blue' ) ) {
   // Continue deletion until all instances are removed
}

Verifying Deletion

This code attempts to delete a user’s ’email’ metadata and verifies if it was successfully deleted.

if ( delete_user_meta( $user_id, 'email' ) ) {
  echo "Email successfully deleted!";
} else {
  echo "Error while deleting email!";
}

Deleting All Meta Data

This example deletes all metadata for a user with a specific key, regardless of the value.

if ( ! delete_user_meta( $user_id, 'extra_data' ) ) {
  echo "Error while deleting extra data!";
}

Remember to replace $user_id with the actual ID of the user.