Add value to usermeta without removing previous values?

update_user_meta( int $user_id, string $meta_key, mixed $meta_value, mixed $prev_value="" ) updates existing user meta based on user_id and meta key. If there are many fields with the same key, you can pass `prev_value’ to tell which field you want to update.

add_user_meta( int $user_id, string $meta_key, mixed $meta_value, bool $unique = false ) adds meta data to a user. It’s last param is unique and it tells whether the same key should not be added (default value is false, so many fields will be created).

On the other hand, if you want to store list o values as one meta, then you’ll have to use arrays or comma separated list.

If we’re talking about dismissed pointers, then we want to use comma separated list, since that is how WP stores the pointers:

$dismissed = array_filter( explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) ) );

if ( ! in_array( $new_pointer, $dismissed ) ) {
    $dismissed[] = $new_pointer;
    $dismissed = implode( ',', $dismissed );

    update_user_meta( get_current_user_id(), 'dismissed_wp_pointers', $dismissed );
}

Leave a Comment