Save Checkbox Group in Widgets Wordpress

2019-05-14 07:46发布

I cannot get multiple checkboxes to work, for the life of me!

Everything else works, including a single checkbox, but I don't know how to make multiple checkboxes.

What I want is the following:

I have a custom post type called Team, with all teammembers in it. I want to make a widget of the posts in Team. I want the checkbox to output all the posts in Team, where the enduser can select who to display.

I tried doing it in arrays, but that didn't work.

My single checkbox is like this:

public function widget( $args, $instance ) {
    $teammember = $instance['teammember'];
}

public function update( $new_instance, $old_instance ) {
    $instance['teammember'] = $new_instance['teammember'];
    return $instance;
}

public function form( $instance ) {
    $teammember = $instance['teammember'];
?>
<p>
    <input id="<?php echo $this->get_field_id('teammember'); ?>" name="<?php echo $this->get_field_name('teammember'); ?>" type="checkbox" value="Name 1" <?php checked( '1', $teammember ); ?>/> Name 1
    <input id="<?php echo $this->get_field_id('teammember'); ?>" name="<?php echo $this->get_field_name('teammember'); ?>" type="checkbox" value="Name 2" <?php checked( '1', $teammember ); ?>/> Name 2
</p>
<?php } ?>

So let's say I have 10 teammember, I want them all to have a checkbox in the widget where the enduser can select what teammember(s) to show.

How do I do that?

1条回答
不美不萌又怎样
2楼-- · 2019-05-14 08:28

In your example the inputs will have a W3C violation because of duplicate IDs. The names will override each other.

The $this->get_field_name('teammember'); will return the same results and override each other.

You need to achieve this as an array.

<?php
    public function form($instance) {
        $teammember = $instance['teammember'];
?>
<p>
    <?php
        foreach($teammember as $id => $name) {
    ?>
    <input id="<?php echo $this->get_field_id('teammember') . $id; ?>" name="<?php echo $this->get_field_name('teammember'); ?>[]" type="checkbox" value="<?php echo $name; ?>" <?php checked('1', $name); ?> />
    <?php
        }
    ?>
</p>
<?php
}
查看更多
登录 后发表回答