1

How do I save options as an array using forms? I don't want to use Settings API.

Here's working form that saves 3 options separately:

<form method="post" enctype="multipart/form-data" action="options.php">
   <?php wp_nonce_field('update-options'); ?>

   <input type="text" name="option1" value="<?php echo get_option('option1');  ?>" />
   <input type="text" name="option2" value="<?php echo get_option('option2'); ?>" />
   <input type="text" name="option3" value="<?php echo get_option('option3'); ?>" />

<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="option1,option2,option3" />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" /></p>
</form>

And here's how it should look for an array, but this method doesn't work (I guess the problem lies in input called page_options:

<form method="post" enctype="multipart/form-data" action="options.php">
   <?php wp_nonce_field('update-options'); ?>
   <?php $options = get_option('my_options'); ?>

   <input type="text" name="option1" value="<?php echo $options['option1']; ?>" />
   <input type="text" name="option2" value="<?php echo $options['option2']; ?>" />
   <input type="text" name="option3" value="<?php echo $options['option3']; ?>" />

<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="my_options" />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" /></p>
</form>

Any ideas?

5

Have you tried...

 <input type="text" name="my_options[option1]" value="<?php echo $options['option1']; ?>" />
 <input type="text" name="my_options[option2]" value="<?php echo $options['option2']; ?>" />
 <input type="text" name="my_options[option3]" value="<?php echo $options['option3']; ?>" />?

I should say though (and maybe you have), that you should register your settings and perform necessary validation checks on the input - or if you really don't want to use the Settings API, disregard it completely and 'manually' collect the form data, check the data, check nonces etc and add to the database.

  • isn't it a dictionary rather than an array? – Kyle KIM Jun 4 '17 at 16:32
  • In PHP an array is used as a dictionary: php.net/manual/en/language.types.array.php – Stephen Harris Jun 5 '17 at 15:14
  • thanks. I use a different language. I solved my problem like my_options[0], my_options[1] ... instead of using String keys because I needed index numbers – Kyle KIM Jun 6 '17 at 12:53

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.