Leave a Reply

2 comments

  1. The reason why in the code, you show there, that delete_post_meta() is run first, is because add_post_meta() is run after it. If the delete wasn’t done first then you would end up with multiple entries stored in the meta table.

    To be honest it would be better to use update_post_meta() rather than both delete_post_meta() and add_post_meta(). The reason for this is that update_post_meta() will try to update the existing value and if it doesn’t exist; will add the value.

  2. Is this code from the core WordPress code or from a plugin or tutorial?

    It is possible that you have invalid old data in the database, like an empty string. To make sure you start with “clean” data (always an integer), it would make sense to first delete all data with this key and then insert your clean data.

    As Brady noted it would be better to use update_post_meta() to replace possible existing values in one step.