Updating WordPress post metadata

I was fighting with a WordPress issue earlier today, and the solution turned out to be pretty simple, and a clear case of me not reading the WordPress developer resources properly.

The situation arose because I was updating a number of post metadata fields and trying to count the number of edits, like this…

$count += (update_post_meta($id, $key, sanitize_text_field($_POST[$key]))===false ? 0 : 1); 

However, when updating a new post, this was giving me a surprisingly high count.  The reason for this is easy to figure out when you read the update_post_meta page…

Return (int|bool) The new meta field ID if a field with the given key didn’t exist and was therefore added, true on successful update, false on failure.

My code is just checking for “not false” and assuming that means an edit has occurred, even if I was actually storing a blank string on a new post, which means adding blank, as there was no metadata there before.

So to get around this, I created my own wrapper function…

function rik_update_post_meta($id, $key, $val) {
  $res = update_post_meta($id, $key, $val);
  if(!is_bool($res)) { //if post meta added (new ID returned)...
    return ($val!==''); //...return false if updating to blank
  return $res; //true if updated, else false

My wrapper function always returns true or false, and doesn’t consider storing blank as a change.  This is because get_post_meta will return a blank string if the metadata doesn’t exist, and I feel this is therefore more consistent.