0

I am looking for a way to save my list of checkboxes as an array within the settings_fields of the plugin. I currently have:

<?php
   $WPusers = get_users( 'orderby=nicename&role=administrator' );
     foreach ( $WPusers as $user ) { ?>
       <input type="checkbox" name="<?php echo $this->plugin_name; ?>[users]" id="<?php echo $this->plugin_name; ?>-users" value="<?php echo $user->ID; ?>" <?php checked( $user->ID, $options['users'], false ); ?> />
       <label for="<?php echo $this->plugin_name; ?>[users<?php echo $user->ID; ?>]"><?php echo $user->display_name; ?></label>
     <?php } ?>

The only thing is that it only saves one option instead of an array of all the checked boxes. I would love to see a way to store all the checked users within one option of the plugin.

Since I am new to WP development and PHP in general this is all quite new for me.

0

Change the [user] to [users][]. Hope that will fix the problem. Now you'll get all the value in associative array within [users]['your-checkbox-data-array'] So your code will be like-

<?php
   $WPusers = get_users( 'orderby=nicename&role=administrator' );
     foreach ( $WPusers as $user ) { ?>
       <input type="checkbox" name="<?php echo $this->plugin_name; ?>[users][]" id="<?php echo $this->plugin_name; ?>-users" value="<?php echo $user->ID; ?>" <?php checked( $user->ID, $options['users'], false ); ?> />
       <label for="<?php echo $this->plugin_name; ?>[users<?php echo $user->ID; ?>]"><?php echo $user->display_name; ?></label>
     <?php } ?>
  • Thank you kind sir! That was the way to do it! I updated the check function as well to check against the array. <input type="checkbox" name="<?php echo $this->plugin_name; ?>[users][]" id="<?php echo $this->plugin_name; ?>-users" value="<?php echo $user->ID; ?>" <?php checked( ( in_array( $user->ID, $options['users'] ) ) ); ?> /> <label for="<?php echo $this->plugin_name; ?>[users<?php echo $user->ID; ?>]"><?php echo $user->display_name; ?></label> – Erik van der Bas Nov 1 '16 at 8:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.