Function and usage of delete_usermeta() in wordpress

Question

Answers ( 1 )

    0
    2024-01-05T21:25:11+00:00

    The delete_usermeta() function in WordPress is designed to remove metadata associated with a user. This function is useful when you need to delete specific information tied to a user account, such as custom preferences or settings. Below is a detailed explanation of the function, its parameters, and a sample usage:

    Function Signature

    delete_usermeta( int $user_id, string $meta_key, mixed $meta_value = '' ): bool
    

    Function Description

    • Purpose: delete_usermeta() is used to remove specific user meta data from the WordPress database. This function is part of the WordPress User Meta API.
    • Behavior: It deletes a metadata entry with the specified $meta_key and $meta_value for a given $user_id. If $meta_value is not specified, it will delete all entries with the given $meta_key for that user.

    Parameters

    1. $user_id (int, required): The ID of the user whose metadata you want to delete. It must be a valid user ID, typically a number.
    2. $meta_key (string, required): The key of the metadata you wish to delete. It identifies the specific piece of user meta data.
    3. $meta_value (mixed, optional): The value of the metadata you wish to delete. If specified, only the metadata entry that matches both the key and the value will be deleted. If left as the default (an empty string), all entries with the specified key will be deleted, regardless of their value.

    Return Value

    • Type: bool
    • Description: Returns true if the deletion is completed successfully. Returns false if the $user_id is not a valid number or if other errors occur during the deletion process.

    Sample Usage

    Here's an example of how you might use delete_usermeta():

    $user_id = 123; // Assuming this is a valid user ID
    $meta_key = 'custom_preference';
    $meta_value = 'blue_theme'; // Optional: Specify this if you only want to delete metadata with this value
    
    $result = delete_usermeta($user_id, $meta_key, $meta_value);
    
    if ($result) {
        echo 'User meta data deleted successfully.';
    } else {
        echo 'Error in deleting user meta data.';
    }
    

    In this example, the function attempts to delete the 'custom_preference' metadata with the value 'blue_theme' for the user with ID 123. It then checks if the operation was successful and outputs a corresponding message.

    Note

    • As of my last update in April 2023, WordPress functions and APIs may have received updates or changes. It's always a good practice to refer to the official WordPress documentation for the most current information.
    • Be cautious when using delete_usermeta() as it can permanently remove data. It's a good practice to backup your database before performing operations that modify it.

Leave an answer