add_settings_field() and register_setting() saving blank options?

Is anyone using the built in add_settings_field() and register_setting() features?

Is there a way to make it not save blank options? Or not save options if the input field doesn’t exist on the page?

I’m looking for some sort of “setting-pre-save” filter that can modify or stop the users options from getting written to the db. Any ideas?

Thanks!

FYI it was the ‘whitelist_options’ filter. Something like this:


public function init(){
    add_filter( 'whitelist_options', array($this, 'whitelist_options'), 100, 1);
}
	
public function whitelist_options($options){

	if(isset($options['member_settings']) && !empty($_POST['option_page']) && $_POST['option_page'] == 'member_settings'){
		// we're saving the techspace member settings area. remove options if we are attempting to save an empty field.
		foreach($options['member_settings'] as $index => $key){
			if(empty($_POST[$key])){
				unset($options['member_settings'][$index]);
			}
		}
	}
	return $options;
}

Hi,

Have you tried removing the name attribute of the fields that you don’t want to save? E.g. with JS?

I’ve bumped into a similar (yet not the same) problem, and removing the name attribute from the input field removed it completely from the $_POST object during the save hook…

Yes tried that with a data-tempname="foo" variable that was replaced with name="foo" on form submit only if the input element wasn’t empty.

It still saved an empty option value.

Even when I completely removed the input element from the screen it would still save an empty value. Hence the filter option above.