Auto-remove custom field with no value on publish

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?

Related posts

Leave a Reply

2 comments

  1. Here is the solution:

    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;
    }
    
  2. wp_insert_post_data is a hook that happens before a database write in the admin panel. You can probably use that to call a function that checks for data, then strips out any empty custom field entries.

    Or, you could use the_content hooks on the front end to strip out empty custom fields before they get displayed to the user.

    Or, if you have control of the theme files, you can just test for data in your custom fields before displaying them.