We are looking at the best way we can delete empty custom fields which are being created by one of our Wordpress plugins.
This can be achieved by adding the following code to our functions.php file.
This works, and prevents the creation of empty custom fields, but this code also prevents us from updating any of our current product(s) status from in stock to out of stock.
Looking for a way to amend the code below, so that it only stops the creation of empty custom fields, without stopping us from being able to put products to zero as out of stock.
Current code:
add_action('save_post','my_cf_check');
function my_cf_check($post_id) {
// verify this is not an auto save routine.
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
//authentication checks
if (!current_user_can('edit_post', $post_id)) return;
//obtain custom field meta for this post
$custom_fields = get_post_custom($post_id);
if(!$custom_fields) return;
foreach($custom_fields as $key=>$custom_field):
//$custom_field 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
$values = array_filter($custom_field);
//After removing 'empty' fields, is array empty?
if(empty($values)):
delete_post_meta($post_id,$key); //Remove post's custom field
endif;
endforeach;
return;
}