Settings API: Setting default option via ‘get_option’ fails

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.)