skip to Main Content

I have data in the metauser table as shown below. As you can see, the data is in the form of a serialized array. How do I push array data? I want to save the post id in the meta bookmark. But if I use add_user_meta() instead it creates data in a new row instead of adding data in value (so there will be 2 meta bookmarks in 1 user with different values). If I use update_user_meta() it just replaces the old new value, not adding (push) the array data. How do I add new data (array) to the meta value?

table usermeta in wordpress

Like the example image below, this is the meta of post_status and comment_status from plugin ulike WordPress. I think when there are new posts or new comments, the value will also increase according to the associated id.

[table ulike_meta from plugin ulike in wordpress2

please, free to edit this question if there is an incorrect or unsuitable word.

Thank You!

2

Answers


  1. You can use get_user_meta function to get value.

    $post_status = get_user_meta( $user_id, 'post_status', true );
    

    Now modify $post_status array as per your requirement. and update
    after it.

    update_user_meta( $user_id, 'post_status', $post_status );
    

    Remember WordPress uses maybe_serialize and maybe_unserialize to save and get value from meta tables.

    Login or Signup to reply.
  2. To store an array as a user meta in the WordPress database you can use the PHP serialize() function. In this example an array will be stored for the current user (as in your screenshot).

    $bookmark = array(
        0 => 3058,
    );
    update_user_meta( get_current_user_id(), '_bookmark_article', serialize($bookmark) );
    

    To modify a serialized array you can use the PHP unserialize() function. In this example, the user meta _bookmark_article will be retrieved, modified and updated:

    // retrieves the value of the user meta "_bookmark_article"
    $bookmark_article = get_user_meta( get_current_user_id(), '_bookmark_article', true );
    // convert value to array
    $bookmark_article = unserialize( $bookmark_article );
    
    // adds a value to the array
    $bookmark_article_updated = $bookmark_article_array[] = 3445;
    // updates an array value based on the key
    $bookmark_article_updated = $bookmark_article_array[0] += 50;
    
    // updates the value of the user meta "_bookmark_article"
    update_user_meta( get_current_user_id(), '_bookmark_article', serialize($bookmark_article_updated) );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search