0

Saving JSON data as meta_value for users in the wp_usermeta table. The JSON data looks something like this:

{
    "user":5,
    "levels":{
        "1":{"first_seen":1614309493,"last_seen":1617368469},
        "2":{"first_seen":1616309493,"last_seen":1617369479},
        "3":{"first_seen":1617309493,"last_seen":1617379121}
        }
}

The "first_seen" value (per level/id) should not change once it has a value saved. The "last_seen" value should be updated each time.

I am using this to save the data when a hook is fired. This - saving data per user, when no data is saved yet, works. BUT updating only the "last_seen" value once a user already has data, is something I am struggling with.

Is it even possible with "add_user_meta" and/or "update_user_meta" to the partly update a value? If not, are there any other solutions to get this working?

I am pretty sure I saw a plugin that handled this by using JSON, but can´t remember the name...

Hope you can help me out! Thanks a lot.

update: As pointed out by Vancode, I also try to use get_user_meta to get the data, change the "last_seen" part and save it again to the database.

With this however - mainly the getting & changing the "last_seen" part, I´m still struggling unfortunately...

1 Answer 1

0

You cannot use update_user_meta on its own here. You would need to get_user_meta first, decode your json into an array, update the last_seen element of the array, re-encode it and only then update_user_meta.

Unless there is a good reason not to, I would consider just saving these as serialized data (to avoid the json step), or even restructure your data to be more granular, saving each bit in its own record, eg with a key of 1_1_first_seen, 1_1_last_seen (where the first number is the user ID and the second number is the level) etc, as without this you're making life very hard for yourself if you ever need to query any of this data in any detailed way.

1
  • Thanks a lot for your reply! I thought about doing it the "own record" way, but my feeling is that this could result in a lot of records. When I have 2500 users * 10-15 levels this would result in a lot of records, where with the other solution it would only be 1 record / row per user, right? I forgot to mention - will update my post - that I use the get_user_meta to get the data, but I seem to have difficulties in the update the '''last_seen''' part only.
    – Elv1s
    Commented Apr 2, 2021 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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