[wp-hackers] How do you store multiple plugin options

Otto otto at ottodestruct.com
Wed Mar 24 15:06:43 UTC 2010


On Tue, Mar 23, 2010 at 6:06 PM, Peter van der Does
<peter at avirtualhome.com> wrote:
> Everybody knows, or at least should know, that storing every variable
> as an option is a bad idea. You usually use an array and store the
> array.
>
> How do you store multiple options.
> What I mean is, you can have general options, options that are to be
> used throughout the plugin. You can have default widget options, so
> when you don't enter a value in the widget this option will be used.
>
> Currently I store this as follows:
> $general=array('key1'=>'value1', 'key2'=>'value2');
> $widget=array('key3'=>'value1', 'key2'=>'value4');
> $option=array('general'=>$general,'widget'=>$widget);
> update_option( 'myplugin', $options );
>
> I also can see it as follows:
> $general=array('key1'=>'value1', 'key2'=>'value2');
> $widget=array('key3'=>'value1', 'key2'=>'value4');
> update_option( 'myplugin-general', $general );
> update_option( 'myplugin-widget', $widget );
>
> So how do you store your options?

I discuss some of this in my Settings API tutorial:
http://ottopress.com/2009/wordpress-settings-api-tutorial/

But, in general, the way you want to do it is as follows: Anything
that you will load all the options for at once (presumably because
you're using all or most of them) should be in one single option. The
majority of plugins should put all their options in one field, for
simplicity. Only rarely do you actually need extra options fields.

The format of that option's value is up to you, but I recommend
against nested arrays in the way you're suggesting there, and would
say a simple array would be better. Simple array lookups are faster
than nested arrays are, and with prefixing of your keys, it's really
just as easy to use.

So instead of this:
$general=array('key1'=>'value1', 'key2'=>'value2');
$widget=array('key3'=>'value1', 'key2'=>'value4');
$option=array('general'=>$general,'widget'=>$widget);

I'd say to do this:
$option=array('general-key1'=>'value1', 'general-key2'=>'value2',
'widget-key3'=>'value1', 'widget-key2'=>'value4');

-Otto


More information about the wp-hackers mailing list