Save and retrieve custom plugin options value

I want to save the value of input data and retrieve it, I have gone through the tutorial of otto press.

I’m new to creating WordPress plugin and what I can’t understand is once I click the Save changes button, the page shows:

Read More

Setting saved

My question is where do the value of input go and how do I retrieve that value in the same page.

Here is my code

add_action('admin_menu', 'add_page');

if ( !function_exists( 'add_page' ) ) {
    //function to add page under setting options in wordpress admin section
    function add_page() {
        add_options_page('New Setting Page', 'New Setting', 'manage_options', 'plugin', 'plugin_options_frontpage');
    }   
}

function plugin_options_frontpage() {
    ?>
    <div class="wrap">
    <h2>New Setting Page title</h2>
    <form action="options.php" method="post">
    <?php settings_fields('plugin_options'); ?>
    <?php do_settings_sections('plugin'); ?>
    <table class="form-table"> 
      <tr valign="top">
        <td colspan="2">
            <input name="Submit" type="submit" class="button button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
        </td>
      </tr>
    </table>
    </form>
    </div>
    <?php
}    

add_action('admin_init', 'plugin_admin_init');

function plugin_admin_init(){
    register_setting( 'plugin_options', 'plugin_options', 'plugin_options_validate' );
    add_settings_section('plugin_main', 'Main Settings', 'plugin_section_text', 'plugin');
    add_settings_field('plugin_text_input1', 'Input 1', 'plugin_input1', 'plugin', 'plugin_main');
    add_settings_field('plugin_text_input2', 'Input 2', 'plugin_input2', 'plugin', 'plugin_main');
}

function plugin_section_text() {
    echo '<p>New input setting to be saved.</p>';
}

function plugin_input1() {
    $options = get_option('plugin_options');
    echo "<input id='plugin_input1' class='normal-text code' name='plugin_options[text_string]' size='30' type='text' value='{$options['text_string']}' />";
}

function plugin_input2() {
    $options = get_option('plugin_options');
    echo "<input id='plugin_input2' class='normal-text code' name='plugin_options[text_string]' size='30' type='text' value='{$options['text_string']}' />";
}

function plugin_options_validate($input) {
    $options = get_option('plugin_options');
    $options['text_string'] = trim($input['text_string']);
    if(!preg_match('/^[a-z0-9]{32}$/i', $options['text_string'])) {
        $options['text_string'] = '';
    }
    return $options;
}

Related posts

Leave a Reply

1 comment

  1. The option will be stored in the table $wp_prefix . "options" as an array.

    You can get the option with $myoptions = get_option('plugin_options'); try var_export( $myoptions ); to see that.

    There is also a hidden page in wp-admin/options.php where you can see all saved options.