You can fix this in 1 of 2 ways:
- change the call to
add_user_meta()
toupdate_user_meta()
when your 1st conditional evals to true. As explained in update_user_meta(), “If the meta field for the user does not exist, it will be added.” - pass
true
as the$unique
(4th) param toadd_user_meta()
. As explained in add_user_meta(), the$unique
param controls “whether the same key should not be added” (i.e., when true, if the meta already exists, another one will not be added; it defaults to false).
In most cases, which is preferred comes down to “style”.
Edit
The same applies to add_post_meta()
vs update_post_meta()
and add_term_meta()
vs update_post_meta()
.
Where #1 or #2 matters is if you’ve hooked into update_{$meta_type}_meta and expect it to always fire. In case #1 (i.e., always use update_user_meta()
) the update_user_meta
action will not fire if the meta does not already exist, since update_user_meta()
will simply call add_user_meta()
if the meta doesn’t ready exist.
Hence, if you care about capturing meta additions, you should generally hook into both update_{$meta_type}_meta
and add_{$meta_type}_meta, even if you always use update_user_meta()
.