WordPress – Custom wp_options entries

What I want

For a theme I’m developing I tried to use the wp_options table in the database.

Read More

I have a custom options page in wp-admin where I have 4 entries with two options like this:

Options

Option 1 Text:
Option 1 Value:

Option 2 Text:
Option 2 Value:

etc.

Now I want to write these Settings into the database.

What I have

For coding this I use these WordPress code snippets:

First I add the options in my functions.php like this:

add_option('option-1-text', '');
add_option('option-1-value', '');

Then I update these options when saving my page like this:

update_option('option-1-text', $option1text);
update_option('option-1-value', $option1value);

The problem

It works. But I don’t think that this is best practice for WordPress. And for these 8 settings I don’t want to create my own table in the database.

Can anyone help me with this?

Related posts

1 comment

  1. The Options API is designed for that purpose and therefore its use is the correct way to work with plugin or theme options. There is also Theme Customization API that allows developers to customize theme’s settings ( and see a preview of those changes in real time) and it can be also used to create and work with various custom theme options.

    For example, creating a new section and adding a checkbox setting control can be done like this:

    add_action( 'customize_register', function( $wp_customize ) {
    
        $wp_customize->add_section( 'my_section' , array( 'title' => 'MY Custom Section' ) );
        $wp_customize->add_setting( 'my_setting' , array( 'default' => false ) );       
        $wp_customize->add_control( 'my_setting', array(
            'label'      => 'My Custom Setting',
            'section'    => 'my_section',
            'settings'   => 'my_setting',
            'type'       => 'checkbox'
        ));
    
    });
    

    And for fetching your setting values use get_theme_mod() function.

    get_theme_mod( 'my_setting' )
    

    Personally when I work with options for the theme I feel more comfortable with Theme API than Settings and Options API because it is easier to use for the same effect.

    A few useful links:

    Settings API
    Options API
    Theme Customization API
    Customizer API
    get theme mod()

Comments are closed.