Custom field is save same empty


How prevent the custom field is save while empty?

Thanks


Hello, I use this code.

// Remove custons fields is empty
add_action('save_post','remove_fields_empty_check', 100);
function remove_fields_empty_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;
}

Hi Miguel,

Could you kindly post the snippet you are using to register your field please? Out of curiosity, why wouldn't you want the empty fields to save?

Thanks,


Hello,

My snippet to create custom fields is:

// Add MetaBox Custom Options
add_action( 'admin_init', 'add_custom_posts_options' );

function add_custom_posts_options() {

 $fields = array(
    array(
      'id' => 'is_landing',
     'label' => 'Landing Page ',
     'type' => 'checkbox',
     'default' => bool
   ),
    // ...
  );

  beans_register_post_meta( $fields, array( true ), 'custom_posts_options', array( 'title' => 'Custom Options', 'context'=> 'side' ) );

}

I would not like to save empty fields to keep clean database.

Thanks,


Thanks for sharing your snippet.

I am afraid there isn't a way to do that in Beans Core. I have added that in the feature requests. For now, you could simply use the update_{$meta_type}_metadata filter (see documentation here) to save the data as you wish.

Happy coding,

Write a reply

Login or register to write a reply, it's free!