When it comes to dealing with options and settings in plugins and themes I’ve tried more ways than I can count, most of which have been throughly unsatisfactory. Whilst the WordPress native option functions let you save an array as a value here’s unfortunately no way to retrieve a singular value from that array at a later date. Let’s face it, no one wants to being doing this every time they need to check something:
$options = get_option( 'my_array_of_options' );
$value = isset( $options['option_i_really_want'] ) ? $options['option_i_really_want'] : false ;
It doesn’t look very pretty and it’s a lot of code duplication when used everywhere.
After experimenting and snooping around other plugins a bit I’ve finally settled on a solution I’m happy with.
Every plugin and theme has a helper file, make sure it’s included before everything else. In it add acme_get_option and acme_get_options functions.
Immediatly after you’ve included the helper.php file set the options up in a global variable so the acme_get_option function can access them.
$_GLOBAL['acme_options'] = acme_get_options();
You can now use acme_get_option() anywhere you like!
Multiple settings
Ok, that’s great, you think, but what about if I’ve got multiple settings pages? When ever I save one it’ll just overwrite the others of they’re all stored in one option array? I’m glad you asked. A simple array_merge will correct that. When registering your settings, define a validation function (which you should anyway) and at the end simple merge the new values with the existing other values and then save the lot.
What if I want an array of options?
Well yes, if you want to save nested arrays then the same problems exist. Having considered it a lot though I think the best solution is to simply not, group your settings by a prefix instead and keep the array at single level. Nested arrays offer no real benefit other than nicely grouping options in the eyes of the developer, the same can be achieved with a prefix.
Alternatives
Static classes – using a class with a static method was actually next on my list, but, other than nicely grouping a load of functions together they don’t really offer any benefits. On the other hand, for PHP