Using separate option names for a bunch of related options is not ideal.
Instead, store options in a single key as a serialized array unless there is a specific reason not too. This way, you’ll only need the one call to add_option()
, update_option()
, and get_option()
which will mean fewer queries being generated overall, particularly (as you noted), when adding and updating values.
// Example function where options are saved under the name wpse242105_options
function wpse242105_options() {
// Example settings array
$settings = array (
'option1' => '0',
'option2' => '0',
'option3' => '0',
'option4' => '1',
'option5' => '1',
'option6' => '0',
'option7' => '1',
);
// Save all of the options under a single option key, wpse242105_options
add_option( 'wpse242105_options', $settings ); // Using add_option() so option will be created if it doesn't exist.
}
add_action( 'init', 'wpse242105_options' );
Once the options have been saved you can get them all in one call to get_option()
.
$saved_options = get_option( 'wpse242105_options' );
print_r( $saved_options );
Output:
Array
(
[option1] => 0
[option2] => 0
[option3] => 0
[option4] => 1
[option5] => 1
[option6] => 0
[option7] => 1
)
Note that WordPress will handle the serialization of the array for you. The option_value
for wpse242105_options
will look like this in the database:
a:7:{s:7:"option1";s:1:"1";s:7:"option2";s:1:"0";s:7:"option3";s:1:"0";s:7:"option4";s:1:"1";s:7:"option5";s:1:"1";s:7:"option6";s:1:"0";s:7:"option7";s:1:"1";}
get_option()
will turn the serialized array back into a PHP array.