diff --git a/classes/elements/WP_Form_Element_Checkboxes.php b/classes/elements/WP_Form_Element_Checkboxes.php index c2ef0e9..15ceffb 100644 --- a/classes/elements/WP_Form_Element_Checkboxes.php +++ b/classes/elements/WP_Form_Element_Checkboxes.php @@ -3,4 +3,11 @@ class WP_Form_Element_Checkboxes extends WP_Form_Element_Multiple { protected $type = 'checkboxes'; protected $default_view = 'WP_Form_View_Checkboxes'; + + public function get_selected() { + if ( !empty($this->value) ) { + return $this->value; + } + return $this->default_value; + } } diff --git a/classes/views/WP_Form_View_Checkboxes.php b/classes/views/WP_Form_View_Checkboxes.php index bae80b1..738c36b 100644 --- a/classes/views/WP_Form_View_Checkboxes.php +++ b/classes/views/WP_Form_View_Checkboxes.php @@ -7,14 +7,19 @@ protected function checkboxes( WP_Form_Element_Checkboxes $element ) { throw new LogicException(__('Cannot render checkbox group without a name', 'wp-forms')); } $options = $element->get_options(); + $selected = (array) $element->get_selected(); $output = ''; foreach ( $options as $key => $label ) { - $output .= $this->checkbox( $key, $label, $attributes ); + $checked = false; + if ( in_array( $key, $selected ) ) { + $checked = true; + } + $output .= $this->checkbox( $key, $label, $attributes, $checked ); } return $output; } - protected function checkbox( $key, $label, $attributes ) { + protected function checkbox( $key, $label, $attributes, $checked ) { $checkbox = WP_Form_Element::create('checkbox') ->set_name($attributes['name'].'[]') ->set_label($label) @@ -32,6 +37,9 @@ protected function checkbox( $key, $label, $attributes ) { foreach ( $attributes as $att => $value ) { $checkbox->set_attribute($att, $value); } + if ( $checked ) { + $checkbox->set_attribute('checked', 'checked'); + } return $checkbox->render(); } }