Differences between add_post_meta and update_post_meta

The question:

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:

Differences between add_post_meta and update_post_meta

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:

Differences between add_post_meta and update_post_meta

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?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment