Storing user metadata as individual values ​​or an array

I am working on a plugin that is going to save about 10 custom meta meta for specific users connected to the plugin. Among these metacharacters we find: address, postal code, occupation, etc.

These meta will only be used by the plugin, and basically (if not always) they will all be fetched from the database together so that they appear as a table in the admin.

So, I'm thinking about the best way to store these values.

I could do this:

add_user_meta( $user_id, 'address', 'kings street 45');
add_user_meta( $user_id, 'zip', '12345');
add_user_meta( $user_id, 'occupation', 'nurse');
... some more meta

      

Or would it be better to do this:

add_user_meta( $user_id, 'plugin_name_user_meta', array(
    'address' => 'kings street 45'
    'zip' => '12345'
    'occupation' => 'nurse')
    ... some more meta
);

      

+4


source to share


2 answers


I disagree with the first answer and I would take your first suggestion.

Why? Because if you use add_user_meta

for each field, you have a separate field in the database for each value. It means:

1) You can do meta and wildcard queries for example. Msgstr "Select all users with ZIP starting at 11". This is not possible if you save the array, especially when the array is saved in serialized format.

Keep this opportunity open! On some day, you may need complex queries on this data, even if it is not.



Check out the WP Meta Query class and even better the WP User Query class:

https://codex.wordpress.org/Class_Reference/WP_Meta_Query

https://codex.wordpress.org/Class_Reference/WP_User_Query#Custom_Field_Parameters

2) You have no shortage of extensibility: since these fields are already stored in the meta table and not in fixed columns, you can add and remove values ​​dynamically.

However, @Juan is right with the prefix hint: you should definitely prefix your meta values ​​to avoid collisions.

+1


source


In WordPress, I prefer to work with arrays because it helps keep my data organized, so I would go the second route. However, if you go first, prefix everyone meta

with a unique ID associated with your plugin.



+3


source







All Articles