Settings API: Setting default option via ‘get_option’ fails

Question
  1. All my options are stored in one array test_hs_options
  2. I have select list settings field ( test_hs_options['duration_months'] ) which stores the selected month (1-12).
  3. For this settings field, I would like to set a default option at 5.
  4. All my attempts at setting the default have failed.
  5. What am I missing?
// Callback for displaying sfield_select_duration.
function cb_test_hs_sfield_select_duration() {

    // get option test_hs_options['duration_months'] value from db.
    // Set to '5' as default if option does not exist.
    $options  = get_option( 'test_hs_options', [ 'duration_months' => '5' ] );

    $duration = $options['duration_months']; // fails!

    var_dump($options); // PHP Notice:  Undefined index: duration_months

    // define the select option values for 'duration' select field.
    $months = array( '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12' );

    // Display select control
    echo '<select id="duration" name="test_hs_options[duration_months]">';
        // loop through option values
        foreach ( $months as $month ) {
            // if saved option matches the option value, select it.
            echo '<option value="' . $month . '" ' . selected( $duration, $month, false ) . '>' . esc_html( $month ) . '</option>';
        }
    echo '</select>';
}

0
sleeper 4 months 0 Answers 10 views 0

Leave an answer