Autoremove empty custom fields

I believe this was my solution to a previous question you had.

I mentioned in that answer that the code didn’t deal with the eventuality of a key with multiple values and only some of which are empty. The reason why is how WordPress treats delete_post_meta

When using delete_post_meta, the first two arguments specify the post and the key of the custom field. You have a third optional argument, which can be used to specify a key-value pair. So…

//Delete all post meta with key $key    
delete_post_meta($post_id,$key)
//Delete all post meta with key $key AND value $value
delete_post_meta($post_id,$key,$value)

The problem is that if $value is empty it treats it like the first case and deletes all post meta for that post and key.

There is a workaround (and perhaps a non-WordPress based one would be more efficient here), the logic is as follows;

  • Identify a key with an empty-value
  • Retrieve all non-empty values
  • Delete the key
  • Re-insert the key, adding only non-empty values

The edited foreach loop;

foreach($custom_fields as $key=>$values):
    //$values is an array of values associated with $key - even if there is only one value. 
    //Filter to remove empty values.
    //Be warned this will remove anything that casts as false, e.g. 0 or false 
    //- if you don't want this, specify a callback.
    //See php documentation on array_filter
    $nonemptyvalues = array_filter($values);

    //If the $nonemptyvalues doesn't match $values then we removed an empty value(s).
    if($nonemptyvalues!=$values):
         //delete key
         delete_post_meta($post_id,$key);

         //re-add key and insert only non-empty values
         foreach($nonemptyvalues as $nonemptyvalue){
             add_post_meta($post_id,$key,$nonemptyvalue);
         }
    endif;  
endforeach;

The above is untested