Using WordPress ‘delete_usermeta’ PHP action

The delete_usermeta WordPress PHP action is used to perform a task after a user’s metadata has been deleted.

Usage

add_action('delete_usermeta', 'my_custom_function', 10, 2);

function my_custom_function($user_id, $meta_key) {
    // your custom code here
}

Parameters

  • $user_id (int) – The user ID of the user whose metadata is being deleted.
  • $meta_key (string) – The metadata key that is being deleted.

More information

See WordPress Developer Resources: delete_usermeta

Examples

Log user meta deletion

Log the deletion of user metadata to a file.

add_action('delete_usermeta', 'log_user_meta_deletion', 10, 2);

function log_user_meta_deletion($user_id, $meta_key) {
    $log_message = "User ID: {$user_id}, Meta Key: {$meta_key} deleted.";
    error_log($log_message, 3, "/var/log/user_meta_deletion.log");
}

Send email notification

Send an email notification to the admin when specific user metadata is deleted.

add_action('delete_usermeta', 'send_email_on_meta_delete', 10, 2);

function send_email_on_meta_delete($user_id, $meta_key) {
    if ($meta_key === 'special_meta_key') {
        $to = '[email protected]';
        $subject = 'User Meta Deleted';
        $message = "User ID: {$user_id} - Meta Key: {$meta_key} has been deleted.";
        wp_mail($to, $subject, $message);
    }
}

Update related metadata when a certain meta key is deleted.

add_action('delete_usermeta', 'update_related_meta', 10, 2);

function update_related_meta($user_id, $meta_key) {
    if ($meta_key === 'primary_meta_key') {
        delete_user_meta($user_id, 'related_meta_key');
    }
}

Delete user posts

Delete all user posts when a specific metadata is deleted.

add_action('delete_usermeta', 'delete_user_posts_on_meta_delete', 10, 2);

function delete_user_posts_on_meta_delete($user_id, $meta_key) {
    if ($meta_key === 'delete_all_posts_meta') {
        $args = array(
            'author' => $user_id,
            'post_type' => 'post',
            'posts_per_page' => -1
        );
        $user_posts = get_posts($args);
        foreach ($user_posts as $post) {
            wp_delete_post($post->ID, true);
        }
    }
}

Add admin notice

Display an admin notice when a specific metadata is deleted.

add_action('delete_usermeta', 'display_admin_notice_on_meta_delete', 10, 2);

function display_admin_notice_on_meta_delete($user_id, $meta_key) {
    if ($meta_key === 'important_meta_key') {
        add_action('admin_notices', 'display_notice_after_meta_delete');
    }
}

function display_notice_after_meta_delete() {
    echo '<div class="notice notice-warning is-dismissible">';
    echo '<p><strong>Important Meta Key</strong> has been deleted.</p>';
    echo '</div>';
}