Is a series of update_option calls safe, performance wise?

0 Votes

I have coded up a function that sets plenty of WordPress options in series.

For example:

update_option('option1', '0');
update_option('option2', '0');
update_option('option3', '0');
update_option('option4', '1');
update_option('option5', '1');
update_option('option6', '0');
update_option('option7', '1');

I understand that what this function does is change values in the database. I am aware that when using get_option, a form of caching takes place, so it could be considered safe. However, for update_option, I am not very sure.

I couldn’t find a function like update_option that accepts multiple options to update. So is doing it like this good for performance? Is there another safer way of doing it?



  1. + 1 -

    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 );


        [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:


    get_option() will turn the serialized array back into a PHP array.

  2. + -

    dez how to make plus mines button.

Please signup or login to answer this question.