Using WordPress ‘insert_custom_user_meta’ PHP filter

The insert_custom_user_meta WordPress PHP Filter allows you to modify a user’s custom meta values and keys right after the user is created or updated, but before the user meta is inserted or updated.

Usage

add_filter('insert_custom_user_meta', 'your_function_name', 10, 4);
function your_function_name($custom_meta, $user, $update, $userdata) {
    // your custom code here
    return $custom_meta;
}

Parameters

  • $custom_meta (array): Array of custom user meta values keyed by meta key.
  • $user (WP_User): User object.
  • $update (bool): Whether the user is being updated rather than created.
  • $userdata (array): The raw array of data passed to wp_insert_user().

More information

See WordPress Developer Resources: insert_custom_user_meta

Examples

Adding a custom meta key-value pair

Add a new custom meta key-value pair to the user.

add_filter('insert_custom_user_meta', 'add_custom_meta_key_value', 10, 4);
function add_custom_meta_key_value($custom_meta, $user, $update, $userdata) {
    $custom_meta['custom_key'] = 'custom_value';
    return $custom_meta;
}

Modifying an existing custom meta value

Modify an existing custom meta value based on certain conditions.

add_filter('insert_custom_user_meta', 'modify_custom_meta_value', 10, 4);
function modify_custom_meta_value($custom_meta, $user, $update, $userdata) {
    if ($custom_meta['some_key'] == 'some_value') {
        $custom_meta['some_key'] = 'new_value';
    }
    return $custom_meta;
}

Removing a custom meta key-value pair

Remove a custom meta key-value pair from the user.

add_filter('insert_custom_user_meta', 'remove_custom_meta_key', 10, 4);
function remove_custom_meta_key($custom_meta, $user, $update, $userdata) {
    unset($custom_meta['custom_key']);
    return $custom_meta;
}

Add custom meta based on user role

Add custom meta based on the user role.

add_filter('insert_custom_user_meta', 'add_meta_based_on_role', 10, 4);
function add_meta_based_on_role($custom_meta, $user, $update, $userdata) {
    if (in_array('administrator', $user->roles)) {
        $custom_meta['admin_meta_key'] = 'admin_meta_value';
    }
    return $custom_meta;
}

Update custom meta based on a specific user ID

Update custom meta for a specific user ID.

add_filter('insert_custom_user_meta', 'update_meta_for_specific_user', 10, 4);
function update_meta_for_specific_user($custom_meta, $user, $update, $userdata) {
    if ($user->ID == 123) {
        $custom_meta['specific_key'] = 'specific_value';
    }
    return $custom_meta;
}