The field name should be uwcc_settings[uwcc_checkbox_field_1][]
, i.e. turn the field into an array.
Secondly, when saved as an array, you should use in_array()
along with the checked()
function. But first, let’s put the uwcc_checkbox_field_1
option’s values into a variable:
$uwcc_checkbox_field_1 = isset( $options['uwcc_checkbox_field_1'] ) ?
(array) $options['uwcc_checkbox_field_1'] : [];
Now you call checked()
like so — the 1
, for example in the first line, means the default value (as in <input value="Mastercard" type="checkbox".../>
) is Mastercard
:
checked( in_array( 'Mastercard', $uwcc_checkbox_field_1 ), 1 )
checked( in_array( 'Visa', $uwcc_checkbox_field_1 ), 1 )
checked( in_array( 'Amex', $uwcc_checkbox_field_1 ), 1 )
The full code, tried & tested working: (re-indented for clarity)
function uwcc_checkbox_field_1_render() {
$options = get_option( 'uwcc_settings', [] );
$uwcc_checkbox_field_1 = isset( $options['uwcc_checkbox_field_1'] )
? (array) $options['uwcc_checkbox_field_1'] : [];
?>
<input type="checkbox" name="uwcc_settings[uwcc_checkbox_field_1][]" <?php checked( in_array( 'Mastercard', $uwcc_checkbox_field_1 ), 1 ); ?> value="Mastercard">
<label>Mastercard</label>
<input type="checkbox" name="uwcc_settings[uwcc_checkbox_field_1][]" <?php checked( in_array( 'Visa', $uwcc_checkbox_field_1 ), 1 ); ?> value="Visa">
<label>Visa</label>
<input type="checkbox" name="uwcc_settings[uwcc_checkbox_field_1][]" <?php checked( in_array( 'Amex', $uwcc_checkbox_field_1 ), 1 ); ?> value="Amex">
<label>Amex</label>
<?php
}
And don’t forget to quote the checkbox values; e.g. 'Mastercard'
and not Mastercard
. See below, assuming that the Mastercard
is not a PHP constant:
checked( $options['uwcc_checkbox_field_1'], Mastercard ) // bad
checked( $options['uwcc_checkbox_field_1'], 'Mastercard' ) // good
checked( in_array( Mastercard, $uwcc_checkbox_field_1 ), 1 ) // bad
checked( in_array( 'Mastercard', $uwcc_checkbox_field_1 ), 1 ) // good