• I am learning WordPress Plugin Development. I need to store Metabox values which are related to Custom Post.

    In this regard where should I use add_post_meta() & where should I use update_post_meta() ?

    • This topic was modified 2 years, 4 months ago by mabufoysal.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Hi @mabufoysal ,

    As per the official documentation of the add_post_meta() function :

    Note that if the given key already exists among custom fields of the specified post, another custom field with the same key is added unless the $unique argument is set to true, in which case, no changes are made. If you want to update the value of an existing key, use the update_post_meta() function instead

    You can also find more information on Custom Metaboxes here.

    I hope this helps you! Happy coding!

    Moderator bcworkz

    (@bcworkz)

    update_post_meta() will add a meta record if one does not exist. From its doc page:

    If the meta field for the post does not exist, it will be added and its ID returned.

    Can be used in place of add_post_meta().

    Personally, I always use update and would very rarely consider using add. Adding would be good (with $unique) if you don’t want to alter an existing value if it already exists.

    Thread Starter mabufoysal

    (@mabufoysal)

    Thanks @bcworkz . I am confused. If I use update_post_meta() where meta field for the post does not exist, then where should I use add_post_meta() ?

    Moderator bcworkz

    (@bcworkz)

    In that situation usage of add_post_meta() is optional. You may use it if you like, but update_post_meta will work as well. Using update_post_meta() exclusively whether the record exists or not means there’s no need check existence to decide which function to use.

    The different behavior of the functions is only evident when the record already exists.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘add_post_meta() & update_post_meta()’ is closed to new replies.