Most WordPress plugins have a settings page where you can turn features on or off etc. But how do you store these settings? The majority of the time you use the built-in functions for saving options:
add_option( 'enable_something', true );
And then you retrieve it:
$enabled = get_option( 'enable_something' );
Now what about a plugin that has dozens and dozens of settings? Well, you end up polluting the options table with just as many entries, all usually prefixed with your plugin name. I don’t like this.
One Option To Rule Them All
Rather combine all your settings into an array and save that single array to the WordPress options table. This function accomplished that:
function save_uber_option($option_name, $key, $value) { //first get the option $options = get_option( $option_name ); if ( !$options ) { //no options have been saved yet, so add it add_option( $option_name, array($key => $value) ); } else { //update the existing option $options[$key] = $value; update_option( $option_name, $options ); } }
A rundown of what this code is doing:
- We first get the option.
- If the option does not already exist then we add it.
- Else, add the key-value to the existing array and update the option.
Now for the retrieval function:
function get_uber_option($option_name, $key, $default = false) { $options = get_option( option_name ); if ( $options ) { return (array_key_exists( $key, $options )) ? $options[$key] : $default; } return $default; }
A rundown of what this code is doing:
- First, get the option.
- If it exists and the key exists in the array, extract the value out of the array
- If all else fails, return a default value.
And finally, a delete function:
function delete_uber_option($option_name, $key) { $options = get_option( $option_name ); if ( $options ) { unset($options[$key]); update_option( $option_name, $options ); } }
A rundown of what this code is doing:
- Again, get the option.
- If it exists then remove the key from the array and update the option with the new array.
It Could Be Better
As with most code, It could be improved. You could wrap these functions in a class and pass in the $option_name via the constructor. This also does not cater for multisite. I will be posting this code on Github soon, as part of my plugin base framework. Watch this space!