Question

I created an option in the options table and I am trying to save data from a custom settings page but I isn't saving.

Below is my code adding the the fields and sections as well as their respective callback functions.

    function wcs_settings() {

    if( !get_option( 'wcs_settings' ) ) {
        add_option( 'wcs_settings' );
    }


    add_settings_section(
        'front_page_settings_section',
        'Front Page Settings',
        'front_page_callback',
        'wcs_settings_page',
    );

    add_settings_field(
        'front-page-slogan',
        'Front Page Slogan',
        'front_page_slogan_callback',
        'wcs_settings_page',
        'front_page_settings_section',
    );

    register_setting(
        'wcs_settings_page',
        'front-page-slogan',
    );

}
add_action( 'admin_init', 'wcs_settings' );

// Callback functions

function front_page_callback() {
    echo '<p>Front Page Setting for the theme.</p>';
}


function front_page_slogan_callback() {

    $options = get_option( 'wcs_settings' );

    $slogan = '';
    if( isset( $options['front-page-slogan'] ) ) {
        $slogan = esc_html( $options['front-page-slogan'] );
    }

    echo '<input type="text" id="front_page_slogan_id" name="wcs_settings[front-page-slogan]" value="' . $slogan . '" />';

}

This is the form I am outputting onto the custom settings page:

<div class="wrap">

<h1><?php esc_html_e( get_admin_page_title() ); ?></h1>

<form method="post" action="options.php">
    <!-- Display necessary hidden fields for settings -->
    <?php settings_fields( 'wcs_settings_page' ) // Slug of page             ?>
    <!-- Display the settings sections for the page -->
    <?php do_settings_sections( 'wcs_settings_page' ); // Slug of Page       ?>
    <!-- Default Submit Button-->
    <?php submit_button(); ?>
</form>
Was it helpful?

Solution

The problem is that you're not passing the correct database option name:

register_setting(
    'wcs_settings_page', // option group
    'front-page-slogan', // database option name
);

So looking at the get_option() call and the HTML input name in your front_page_slogan_callback(), the correct option name is wcs_settings:

register_setting(
    'wcs_settings_page', // option group
    'wcs_settings',      // database option name
);

Check the reference if you haven't already done so.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top