I'm working on a plugin that will allow people to favorite authors on WP site.

When you click on Favorite this author button, it will send author ID to below function and save that value in DB.

Below is the code I save value to FAV_AUTHORS_META_KEY in wp_usermeta table.

$user_id = fav_authors_get_user_id();
$fav_author_id = 2;
update_user_meta( $user_id, FAV_AUTHORS_META_KEY, $fav_author_id );

If I have author ID 2, it will save that on DB. However, when I send different author ID, update_user_meta will override existing value instead of adding the new value.

How do I make it keep the existing value and add new value on the top of it?


There's no built-in functionality to append meta values you'll need to do it manually. If you plan on adding multiple values I would suggest saving it as an array but it will serialize it in the database which will make it harder to run WP_Meta_Query on.

$user_id        = fav_authors_get_user_id();
$fav_author_id  = 2;
$author_list    = get_user_meta( $user_id, FAV_AUTHORS_META_KEY, true );

if( empty( $author_list ) ) {   // There was no meta_value, set an array.
    update_user_meta( $user_id, FAV_AUTHORS_META_KEY, array( $fav_author_id ) );
} else {
    $author_arr = ( is_array( $author_list ) ) ? $author_list : array( $author_list );  // Added in case current value is not an array already.
    $author_arr[] = $fav_author_id;
    update_user_meta( $user_id, FAV_AUTHORS_META_KEY, $author_arr );

I'm assuming what you have in place currently is not an array so I add an inline-conditional inside the else statement to convert any single values to an array. Note that you must pass true to get_user_meta() so that it unserializes our array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.