WordPress settings page options not updating backend

I’m developing a WordPress plugin, and I have been basing my admin page development off of the Codex’s custom settings page example. I have been unable to get it to update the setting in the wp_options db, and I can’t seem to find a good explanation as to what I’ve done wrong. When I click ‘save settings’, the page refreshes and a bar pops up at the top saying the settings were saved properly, but nothing shows up in wp_options, and the text input box isn’t populated with the updated value.

Here’s what I have:

Admin init section:

function secg_settings_init() {
    register_setting( 'secg', 'secg_options' );
    add_settings_section(
        'secg_section_developers',
        __( 'API Keys.', 'secg' ),
        'secg_section_developers_cb',
        'secg'
    );
    add_settings_field(
        'secg_field_test_secret_key', 
        __( 'test-secret-key', 'secg' ),
        'secg_field_test_secret_key_cb',
        'secg',
        'secg_section_developers',
        [
            'label_for' => 'secg_field_test_secret_key',
            'id' => 'test-secret-key'
        ]
    );
}
add_action( 'admin_init', 'secg_settings_init' );

Section and field Callbacks:

function secg_section_developers_cb( $args ) {
    ?>
    <p id="<?php echo esc_attr( $args['id'] ); ?>"><?php esc_html_e( 'Section Developers Cb.', 'secg' ); ?></p>
    <?php
}

function secg_field_test_secret_key_cb( $args ) {
    $options = secg_option();
    ?>
    <input type="text" 
           name="secg_options[<?php echo esc_attr( $args['label_for'] ); ?>]" 
           id="<?php echo esc_attr( $args['label_for'] ); ?>" 
           value="<?php $options[ $args['label_for'] ] ?>" />
    <?php
}

Add Page:

function secg_options_page() {
    add_menu_page(
    'My Plugin',
    'Plugin Options',
    'manage_options',
    'secg',
    'secg_options_page_html'
    );
}
add_action( 'admin_menu', 'secg_options_page' );

Handler for setting default values:

function secg_option() {
    $default = array(
        'secg_field_test_secret_key' => 'test secret key'
    );
    return get_option('secg_options', $default);
}

And finally, the page itself:

function secg_options_page_html() {
   if ( ! current_user_can( 'manage_options' ) ) {
      return;
   }

   if ( isset( $_GET['settings-updated'] ) ) {
       add_settings_error( 'secg_messages', 'secg_message', __( 'Settings Saved', 'secg' ), 'updated' );
   }

   settings_errors( 'secg_messages' );
   ?>
   <div class="wrap">
       <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
       <form action="options.php" method="post">
           <?php
           settings_fields( 'secg' );
           do_settings_sections( 'secg' );
           submit_button( 'Save Settings' );
           ?>
       </form>
   </div>
   <?php
}

Thanks!

Read more here: WordPress settings page options not updating backend

Leave a Reply

Your email address will not be published. Required fields are marked *