WordPress theme options and insert default value for serialize data

How to add default values for theme options? Currently I use basic option from this site

The sample will stored option value in serialize on database. When we activate the theme, there is no value in database at first time until we click Save Changes button.

Read More

Now I want add default value when theme activate something like this.

option_id   blog_id     option_name     option_value                                              autoload 
152           0           theme_data      a:16:{s:12:"html_doctype";s:1:"1";s:14:"header_fav...     yes

Or how do I tweak current sample option to save not in serialize to database

option_id   blog_id     option_name     option_value    autoload 
152           0           html_doctype    1               yes

Let me know.

Related posts

Leave a Reply

1 comment

  1. Loop over your array of options and generate a set of defaults from that..

    Let’s imagine your array looks something like this.. (but obviously bigger)..

    $your_options = array(  
        array( 
            'name' => 'option-one',
            'desc' => 'Option one description',
            'type' => 'text',
            'std'  => 'default_value'
        ),
        ..and so on.. for each option..
    );
    

    First check if you have options, if not, it’s the first install so you can set defaults.

    $my_var_that_holds_options = get_option( 'your_theme_options_name' );
    if( !$my_var_that_holds_options ) {
        // Do code to setup defaults
    }
    

    The code to setup defaults will of course go where i’ve put // Do code to setup defaults.

    First, create an array to hold the defaults and loop over the options array to build the new defaults array.

    $defaults = array();
    foreach( $your_options_var as $option_data ) {
        $defaults[$option_data['name']] = $option_data['std'];
    }
    

    By the end you’ll have an array of option names and default values, which you can then send to the database.

    update_option( 'your_theme_options_name', $defaults );
    

    If you code needs to loop over the options to set boxes checked, etc.. simply call get_option again after you’ve saved the defaults..

    $my_var_that_holds_options = get_option( 'your_theme_options_name' );
    

    Or use the defaults array.

    $my_var_that_holds_options = $defaults;
    

    I’ve had to be quite general with the example, because the approach will differ depending on how your options array is structured.

    The important factor here is to ensure your array of options holds a “default” value(std in the example) for each option else you’ve got nothing to form your default values from.

    I’ve converted themes to do this a handful of times, if you have trouble implementing this feel free to pastebin your file with the options array and i’ll take a look.