Mental note: Set ‘register_meta’s ‘single’ parameter appropriately or you end up with data across multiple custom fields

This is a mental note for my own future reference after spending several hours trying to debug why some data was getting magically broken apart into multiple meta data fields.

In this case I was submitting a string of JSON data (created using JSON.stringify) via $.ajax in jQuery to create a ‘user_meta’ field via the WP Rest API. I could see from the response after successfully posting that the data was breaking up into multiple parts and was showing up as an array in the Ajax response, sure enough looking at the data in the WordPress ‘user_meta’ table I could see that there were a whole load of entries created from pieces of the single string I had sent.

After searching online for solutions and trying quite a few things I managed to narrow it down to which bit of code might be the cause, I was struggling to figure out whether it was happening during the AJAX request or on the server within WordPress.

However, I was aware that when rendering meta data using ‘get_user_meta‘ or ‘get_post_meta‘ that it will bring up an array as the default format as it is possible to have multiple meta fields with the same name, so when requesting a meta field you can set the ‘$single’ parameter to ‘true’ and this will return only a single value.

However, I hadn’t realised that you can actually specify that the fields are only to ever have a single instance when you register them using ‘register_meta‘, after setting this parameter my submitted JSON string happily went into a single user_meta field!

You can set the meta field to use a single parameter when registering like so:

register_meta( 'user', 'my_meta_fieldname', array( 'type' => 'string', 'single' => true ) );

Hopefully this will stay in my head now and I’ll remember if this happens again!

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.