0
  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>';
}

1 Answer 1

1

I guess the problem is when

  • you do have a value for test_hs_options
  • but that value does not have a 'duration_months'

? The default array you're supplying will only be used when there is no test_hs_options in the database: this code won't add a duration_months to a non-empty array that does not have one.

Instead you can check is_array and isset to check if $options has a duration_months value, e.g.

// 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' );

if ( is_array( $options ) && isset( $options['duration_months'] ) ) {
    $duration = $options['duration_months'];
} else {
    $duration = 5;
}

(I expect you could probably also just use if ( $options && ... ) rather than if ( is_array( $options) && ... ) too, i.e. just testing if $options evaluates to true rather than if it's explicitly an array.)

1
  • Yessir! That did it. Thanks!
    – sleeper
    Oct 4, 2020 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.