WordPress Plugin Dev: Using array for WP options

I am busy dabbling with writing a WP plugin and hitting a bit of a problem.

I believe its best practice to store wp options to an array rather than individually which is great no probs.

Read More

I have two pages. Page one which updates for example:

$xyz_options['api_user']; 
$xyz_options['api_key'];

Page two which say has:

$xyz_options['site_bgcolor'];
$xyz_options['site_fontcolor'];

However when updating from either of the pages it empties the other pages settings when using the built in wordpress form building and so forth. I am wondering if I would be better breaking away from the built in methods would be best or is there another way using WP methods that I have missed.

A quick example. Say I first set api_user and api_key with 1 and abc123. Then go to style page and update site_bgcolor with #fff and site_fontcolor with #000 it updates the colors but the api_user and api_key values vanish from the $xyz_options array pulled from wp_options.

Hope that makes sense.

Thanks guys in advance any pointers would be great.

Related posts

Leave a Reply

1 comment

  1. If you are using the Settings API then you don’t have to save the options, that’s done for you. So when using an array to store the options your validation function should get an array of all existing options, update only the changed and return that array.

    Something like this:

    function my_settings_option_validate( $input ) {
        //do regular validation stuff
        //...
        //...
    
        //get all options
        $options = get_option('my_plugin_options');
        //update only the neede options
        foreach ($input as $key => $value){
            $options[$key] = $value;
        }
        //return all options
        return $options;
    }