- All my options are stored in one array
test_hs_options - I have select list settings field (
test_hs_options['duration_months']) which stores the selected month (1-12). - For this settings field, I would like to set a default option at 5.
- All my attempts at setting the default have failed.
- 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>';
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0