How to set up default values for a plugin?

What is the best way to go about setting up default values for a plugin? Should I just insert those values into the wp_options table?

AND…if that’s the best way to go about it, I have another question. My options are listed as a group which currently looks like:

Read More

a:4:{s:26:”nc_location_drop_down_zoom”;s:2:”14″;s:17:”nc_location_width”;s:3:”200″;s:29:”nc_location_drop_down_maptype”;s:7:”roadmap”;s:11:”text_string”;s:0:””;}

Is this a serialized array? How do I do an insert like this into the table? (I realized this is more of an sql question…)

Related posts

Leave a Reply

4 comments

  1. You should do defaults at the time of pulling the data out. Never insert default values into the database. Defaults are default. Options in the DB override defaults.

    How to do defaults for a serialized options array:

    $defaults = array(
      'default1' => '1',
      'default2' => '2',
    );
    $options = wp_parse_args(get_option('plugin_options'), $defaults);
    
  2. In addition to the answer by Otto.

    If you have the multidimensional options array and you still want it to merge with the array of defaults, use the following function in place of wp_parse_args():

    <?php
    function meks_wp_parse_args( &$a, $b ) {
        $a = (array) $a;
        $b = (array) $b;
        $result = $b;
        foreach ( $a as $k => &$v ) {
            if ( is_array( $v ) && isset( $result[ $k ] ) ) {
                $result[ $k ] = meks_wp_parse_args( $v, $result[ $k ] );
            } else {
                $result[ $k ] = $v;
            }
        }
        return $result;
    }
    

    For example,

    <?php
    $defaults = array(
        'setting-1' => array(
            'option-1' => 1,
            'option-2' => 0,
        ),
        'setting-2' => 1
    );
    
    // Only variables are passed to the function by reference (Strict Standards warning)
    $options = get_option('plugin_options');
    $options = meks_wp_parse_args($options, $defaults);
    

    The recursive function was found here.

  3. Use add_option. If you use add_option existing options will not be updated and checks are performed to ensure that you aren’t adding a protected WordPress option.

    See add_option at developer.wordpress.org

    // Activation
    function name_plugin_activation(){
        do_action( 'name_plugin_default_options' );
    }
    register_activation_hook( __FILE__, 'name_plugin_activation' );
    
    
    // Set default values here
    function name_plugin_default_values(){
    
        // Form settings
        add_option('name_form_to', 'info@example.com');
        add_option('name_form_subject', 'New');
    
    
    }
    add_action( 'name_plugin_default_options', 'name_plugin_default_values' );