Theme Customization API options on install

I’m working on a theme that use the WordPress Theme Customization API.

Everything is working as it should, except on initial theme install.

Read More

Some of my options need to be set straight away on theme install.

After looking around it seems that setting the default arg in the add_setting option should set the option right away, but it’s not.

Here’s a short excerpt of my code:

add_action( 'customize_register', 'generate_customize_register' );
function generate_customize_register( $wp_customize ) {

    // Add Layout section
    $wp_customize->add_section(
    'layout_section',
        array(
            'title' => __( 'Layout', 'generate' ),
            'capability' => 'edit_theme_options',
            'description' => __( 'Allows you to edit your theme's layout.', 'generate' ),
            'priority' => 30
        )
    );

    // Add Header Layout setting
    $wp_customize->add_setting(
        // ID
        'generate_settings[header_layout_setting]',
        // Arguments array
        array(
            'default' => 'fluid-header',
            'type' => 'option'
        )
    );

    // Add Header Layout control
    $wp_customize->add_control(
    // ID
    'header_layout_control',
    // Arguments array
    array(
        'type' => 'select',
        'label' => __( 'Header Layout', 'generate' ),
        'section' => 'layout_section',
        'choices' => array(
            'fluid-header' => __( 'Fluid / Full Width', 'generate' ),
            'contained-header' => __( 'Contained', 'generate' )
        ),
        // This last one must match setting ID from above
        'settings' => 'generate_settings[header_layout_setting]',
        'priority' => 1
    )
);
}

As you can see, I created a section, a setting with a default and a control for that setting.

When I go to the Theme Customizer and save the options, a generate_settings table is created in the database with the options inside, as it should be.

However, on a fresh install of the theme, if I go into the database, no generate_settings table exists – the settings are only added to the database when I go into the Theme Customizer and save the options.

Am I doing something wrong? Is there anything I can do to populate the database with these settings on fresh theme install?

Thanks!

Related posts

Leave a Reply

1 comment

  1. Use default values when you fetch the settings. Never store defaults in the database.

    Example:

    $defaults = array (
        'foo' => 'bar'
    );
    
    $options = get_option( 'my_theme_options', $defaults );
    
    echo $options['foo'];