[wp-hackers] Removing empty values from serialized array

Andrew Nacin wp at andrewnacin.com
Thu Aug 5 18:14:00 UTC 2010


On Thu, Aug 5, 2010 at 1:44 PM, Dan Gayle <dangayle at gmail.com> wrote:

> I have an options setting page that uses the register_setting() and
> settings_fields() functions to store my data in a serialized array,
> following the example set by Ozh here:
>
> http://planetozh.com/blog/2009/05/handling-plugins-options-in-wordpress-28-with-register_setting/
>
> When this field is unchecked, the key/value pair in the ozh_sample
> array is completely removed:
> <input name="pms_options[option1]" type="checkbox" value="1" <?php if
> (isset($options['option1'])) checked('1', $options['option1']); ?> />
>
> When this field is left blank, however, the value is blank, but the key
> remains:
> <input type="text" name="pms_options[affiliateID]" value="<?php echo
> (isset($options['affiliateID']) ) ? $options['affiliateID'] : NULL ;
> ?>
>
> So my question is twofold: why does the checkbox go away completely,
> and how can I get an empty options array key to go away? I've tried
> unsetting it, setting it to NULL, everything I can think of. How can
> you get rid of an empty value from a serialized array?


In addition to Otto's excellent advice for using $input and $output, here's
some additional background:

Checkboxes only send data if they are checked. The simplest way to handle
this normally is to use empty() -- $checkbox_value = !empty(
$_POST['checkbox_field'] );. If you ever need to remove keys with empty
values from an array, simply pass the array through array_filter() without a
callback.

That said, use the $input/$output technique. It's definitely the appropriate
way to leverage a sanitization callback.

Nacin


More information about the wp-hackers mailing list