I am struggling with a common issue that many people appear to have encountered over the years. In creating a widget I need a series of radio buttons. Using the code below I can create and show the radio buttons, yet it does not seem to save the value to the database, showing all as unchecked when I hit the save button and nothing is returned on the widget front end.
I believe it is how the radio buttons themselves are declared but do struggle with this level of coding. Is it to do with the $this->get_field_id('') tags not properly declared? I have tried many different permutations but with no luck.
I appreciate any help you can provide.
// 1
function Widget_case_study() {
parent::WP_Widget(false, $name = __('Radio buttons', 'radio_buttons') );
}
// 2
function form($instance) {
$radio_buttons = esc_attr($instance['radio_buttons']);
?>
<p>
<label for="<?php echo $this->get_field_id('text_area'); ?>">
<?php echo('Radio buttons'); ?>
</label><br>
<label for="<?php echo $this->get_field_id('radio_option_1'); ?>">
<?php _e('Option 1:'.$radio_buttons); ?>
<input class="" id="<?php echo $this->get_field_id('radio_option_1'); ?>" name="<?php echo $this->get_field_id('radio_buttons'); ?>" type="radio" value="radio_option_1" <?php if($radio_buttons === 'radio_option_1'){ echo 'checked="checked"'; } ?> />
</label><br>
<label for="<?php echo $this->get_field_id('radio_option_2'); ?>">
<?php _e('Option 2:'.$radio_buttons); ?>
<input class="" id="<?php echo $this->get_field_id('radio_option_2'); ?>" name="<?php echo $this->get_field_id('radio_buttons'); ?>" type="radio" value="radio_option_2" <?php if($radio_option_1 === 'radio_option_2'){ echo 'checked="checked"'; } ?> />
</label>
</p>
<?php
}
// 3
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['radio_buttons'] = strip_tags($new_instance['radio_buttons']);
return $instance;
}
// 4
function widget($args, $instance) {
extract( $args );
$radio_buttons = $instance['radio_buttons'];
?>
<?php echo $before_widget; ?>
<p>Radio button value/status: <?php echo $radio_buttons; ?></p>
<?php echo $after_widget; ?>
<?php
}