it is not the first i see that we “delete” a post meta even if it does not exist : example :
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
So if $count is empty, so if it does not exist in the database, we first delete the post meta? Why ? Thanks for your answer
The reason why in the code, you show there, that
delete_post_meta()
is run first, is becauseadd_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 bothdelete_post_meta()
andadd_post_meta()
. The reason for this is thatupdate_post_meta()
will try to update the existing value and if it doesn’t exist; will add the value.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.