WordPress – How to save default values in theme options page?

If you are a wordpress plugin or theme developer, when creating a theme options page, have you ever wondered why you get Notice: undefined index warnings, thrown by the wordpress debugger. This because when you activate the theme, there is absolutely no values initialized (not even empty values). I am assuming that you are storing the options page value in a single array.  It is absolutely essential to store initial theme default values, in the wordpress database.

While writing this article, I am simply assuming that you know how to create a theme options page and storing the values as a single array. I am not going to do deep in this. Here is a typical example, which stores the social links in the options page.

register_setting( 'mytheme-option-group', 'mytheme-options' ,'mytheme_options_validate');
settings_fields( 'mytheme-option-group' );
do_settings_sections( 'mytheme-option-group' );

With this code, your theme options page stores all your theme option values in a single array mytheme-options

Now Lets load the theme defaults and we properly do it neatly by wordpress hooks, according to wordpress standards. This snippet of code loads the initial default values and saves to wordpress database. Adding a hook through ‘after_theme_setup’ kickstarts everything.

function mytheme_defaults() {

$defaults = array (
                'logo' => '',
                'favicon' => '',
                'footer' => '',
                'facebook-link' => '',
                'twitter-link' => '',
                'google-plus-link' => '',

                );

return $defaults;                    

}
function mytheme_setup()
$mytheme_settings = get_option('mytheme-options');

if($mytheme_settings === false) {
    $mytheme_settings = mytheme_defaults();
}

update_option('mytneme-options', $mytheme_settings);

}
add_action ('after_setup_theme','mytheme_setup');

That should save all the default theme option values into the wordpress database. You can pull the values using

$mytheme_settings = get_options(‘mytheme-options’);

Thanks to Chip Bennett article, which opened my eyes on this topic.