I got some plugins that auto-generates custom fields. Does anyone know how to automatically remove empty custom fields from post when I press “publish”?
A check I can put in my functions.php
that does a check and removes the custom field if there is no value?
Demilio, unfortunately the WordPress API seems to assume that custom fields do not have an ’empty’ value, in the sense that
update_post_meta
anddelete_post_meta
, if given''
as the (previous) meta value perform the update/delete operation for all values for that key.This makes it difficult, for instance, if a custom field key has multiple values associated with it, some of which are empty and want to be removed.
Below is the basic logic: It will only remove fields where all associated fields are ’empty’. Exactly what ‘empty‘ means, you can decide by specifying a callback to
array_filter
, by default, as used in the code below this includes ‘0’, false etc.The hook you are after is
save_post
. This is fired after the post and all it’s post-meta, has been saved having clicked ‘update’/’publish’, but also on auto-saves…As noted above, if a custom field key has multiple values associated with it, some of which are empty – they will not be removed. This will probably be ok for your use. There seems to be no easy ‘WordPress’ way around this. One way would be a custom MYSQL statement.
Thanks Stephen Harris! You rock!
Additionally, if you want to do this only for specific fields, you can put your specific values in an array, and compare it to the $custom_fields array with
array_intersect()
.