Skip to content

Instantly share code, notes, and snippets.

@mbrughi
Last active October 21, 2021 09:02
Show Gist options
  • Save mbrughi/722f4e686238d4aee4d1ebaa5a2b6740 to your computer and use it in GitHub Desktop.
Save mbrughi/722f4e686238d4aee4d1ebaa5a2b6740 to your computer and use it in GitHub Desktop.
Widget sampte to test Checkbox field
class MY_Widget extends WP_Widget {
public function __construct() {
parent::__construct( 'my_widget', 'My Widget', array(
'classname' => 'my-widget',
'description' => 'Testing checkbox fields.',
) );
}
public function widget( $args, $instance ) {
echo $args['before_widget'];
echo '<pre>'; var_dump( $instance ); echo '</pre>';
echo $args['after_widget'];
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['cb1'] = isset( $new_instance['cb1'] ) ? 'yes' : 'no';
$instance['cb2'] = isset( $new_instance['cb2'] ) ? 'yes' : 'no';
return $instance;
}
public function form( $instance ) {
$instance = wp_parse_args(
(array) $instance,
// The default options.
array(
'cb1' => 'yes', // checked by default
'cb2' => 'no', // not checked by default
)
);
?>
<p>
<input type="checkbox" id="<?php echo $this->get_field_id( 'cb1' ); ?>" name="<?php echo $this->get_field_name( 'cb1' ); ?>" value="yes"<?php checked( 'yes', $instance['cb1'] ); ?>>
<label for="<?php echo $this->get_field_id( 'cb1' ); ?>">Checkbox #1</label><br>
<input type="checkbox" id="<?php echo $this->get_field_id( 'cb2' ); ?>" name="<?php echo $this->get_field_name( 'cb2' ); ?>" value="yes"<?php checked( 'yes', $instance['cb2'] ); ?>>
<label for="<?php echo $this->get_field_id( 'cb2' ); ?>">Checkbox #2</label>
</p>
<?php
}
}
/*-----------------------------------------------------------------------------------*/
/* REGISTRO IL WIDGET TEST */
/*-----------------------------------------------------------------------------------*/
if (!function_exists('test_load_post_widgets')) {
function test_load_post_widgets() {
register_widget( 'MY_Widget' );
}
add_action('widgets_init', 'test_load_post_widgets');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment