We have a lot of rogue custom fields. I feel that we can clear significant space in the DB if we remove the blank values. If I query my database with the following:
select * from wp_postmeta where meta_value = ''
I get 871038 (!)
My question is, is it safe to delete these? Are there any potential issues that could arise from doing this?
We have a lot of rogue custom fields. I feel that we can clear significant space in the DB if we remove the blank values. If I query my database with the following:
select * from wp_postmeta where meta_value = ''
I get 871038 (!)
My question is, is it safe to delete these? Are there any potential issues that could arise from doing this?
Share Improve this question asked May 6, 2015 at 16:26 psorensenpsorensen 4976 silver badges17 bronze badges 2- did you ever try this? Did it work? – Kody Commented Feb 8, 2018 at 18:40
- Also keen to know. I am also doing it to remove the number of records.... seems like a logical choice to me! – Rodney Commented Jan 19, 2020 at 6:45
2 Answers
Reset to default 7You should be fine deleting empty custom fields.
The main reason is, that get_post_meta( $id, 'metakey', true )
returns an empty string if the field is not set, so it is the same as having an empty record set.
get_post_meta( $id, 'metakey', false )
, returns an empty array if no value is set, so you should be fine too.
The only problem you could face is with getting all metadata at once (get_post_meta( $id )
), because in the return to this call the empty values are set, but they are not set, if there is no record in the database. This could cause a few PHP_WARNING
s, but you should be okay.
As @fischi pointed out, it should be safe to delete empty values because get_post_meta()
returns the same value for non-existent and empty meta keys,
unless you somehow rely on the keys being set when fetching all metadata at once.
WP 3.1 introduced the filters add_{$meta_type}_metadata
and update_{$meta_type}_metadata
that you can use to clean up empty values or even prevent them from being saved in the database:
https://codex.wordpress/Plugin_API/Filter_Reference/update_(meta_type)_metadata
For example, you can intercept and delete falsy values for all keys containing 'my_prefix' like this:
add_filter('update_post_metadata', function($check, $object_id, $meta_key, $meta_value, $prev_value) {
if(strpos($meta_key, 'my_prefix')) {
if(empty($meta_value)) {
delete_post_meta($object_id, $meta_key, $prev_value);
return true; //stop update
}
}
return null; //do update
}, 10, 5);
Note that this won't clean up any already existing records.