WordPress REST API returns error when updating quoted JSON data

My particular situation involved updating a user via REST API with a custom registered user meta.  The meta updates correctly the first time, and any time there is a change. However an error is thrown if the user update includes the unchanged user meta (i.e. I’m updating the user’s first name, but my solution includes all fields with each update). The user meta value was a quoted JSON object, but this also applies to other serialized values. This also occurs with custom meta for other types besides users, like posts or comments.

The server returns a 500 HTTP status, with the following response:

{“code”:”rest_meta_database_error”,”message”:”Could not update meta value in database.”,”data”:{“key”:”my_custom_meta_key”,”status”:500}}

Credit for identifying this bug goes to Corey Salzano. Corey’s solution is to first pull the data, and if there’s no change, omit it in the update request. I didn’t want to add another request to the server, so I came up with a server-side solution. It is provided below with no guarantees!

Note that you will have to change the hook update_user_metadata  and $meta_type  and $serialized_meta_keys  for your particular situation.

Leave a Reply