Differences between add_post_meta and update_post_meta

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x