3

I have a question about add_post_meta and update_post_meta.

When i am using add_post_meta:

add_post_meta($id, 'my_meta_key', 'my_meta_value_1');
add_post_meta($id, 'my_meta_key', 'my_meta_value_2');
add_post_meta($id, 'my_meta_key', 'my_meta_value_3');

It will give me something like that:

Table 1

Now when i get this data like this:

get_post_meta(42, 'my_meta_key')

I get:

array (size=3)
  0 => string 'my_meta_value_1' (length=15)
  1 => string 'my_meta_value_2' (length=15)
  2 => string 'my_meta_value_3' (length=15)

But i can do this in another way, like this:

update_post_meta(42, 'my_meta_key', [
    'my_meta_value_1',
    'my_meta_value_2',
    'my_meta_value_3',
]);

Then in database i have:

Table 2

Now when i get this data:

get_post_meta(42, 'my_meta_key', true)

I have same result:

array (size=3)
  0 => string 'my_meta_value_1' (length=15)
  1 => string 'my_meta_value_2' (length=15)
  2 => string 'my_meta_value_3' (length=15)

So I have a question, are either of these two ways of saving data better than the other?

Or either of these methods is better for data retrieval?

1 Answer 1

4

This:

update_post_meta(42, 'my_meta_key', [
    'my_meta_value_1',
    'my_meta_value_2',
    'my_meta_value_3',
]);

Changes a single post meta, but the value is an array, and you can't put a array in the database, it wants a string for that column. So WordPress serializes it into a string and saves the result.

So I have a question, are either of these two ways of saving data better than the other?

Yes! Serialized data is bad, it's difficult to query (sometimes imposssible), has a tiny additional overhead, and it exposes you to object deserialisation attacks.

If you want to store a list of 10 things, store 10 meta, not 1 meta with an array. If you really must do it, turn it into a comma separated list first or JSON encode it.

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.