WP get_option: A Practical Guide Save Values to Database

This post will benefit you if you’re creating a plugin or hard-coding a theme that involves of using `get_option` which saves data to the database. If you have plenty of fields or name attributes in the form, this will leave a handful of `get_option` keys in the `wp-option` table which will be unmanageable to handle if you require to have plenty of fields. The practical way to is consolidate your data into only one key by using an array.

Let’s take a look on the example of creating a form below:

Input Fields with Array Name Attribute

 
<form method="post" action="<?php echo esc_attr($_SERVER['request_uri']); ?>">
   <?php wp_nonce_field('oooops_option_action','oooops_option_field'); ?>
   <h2 class="oooops-title"><?php _e('General', 'oooops-txt'); ?></h2>
   <p><?php _e('This section is the main settings.', 'oooops-txt'); ?></p>
   <table class="form-table">
      <tbody>
         <tr>
            <th scope="row"><label for="oooops-field-1"><?php _e('Field Test 1', 'oooops-txt'); ?></label></th>
            <td>
               <input id="oooops-field-1" class="oooops-field-1 regular-text" name="oooops_options[]" type="text" value="<?php echo oooops_get_option('oooops_options', '', 0) ?>">
               <p class="oooops-description"><?php _e('Important Notice: You have to click save button first.', 'oooops-txt'); ?></p>
            </td>
         </tr>
         <tr>
            <th scope="row"><label for="oooops-field-2"><?php _e('Field Test 2', 'oooops-txt'); ?></label></th>
            <td><input class="oooops-field-2 regular-text" name="oooops_options[]" type="text" value="<?php echo oooops_get_option('oooops_options', 'default text', 1) ?>"></td>
         </tr>
         <tr>
            <th>
               <p class="submit"><input type="submit" name="submit" class="button-primary" value="<?php _e('Save Changes', 'oooops-txt'); ?>"></p>
            </th>
         </tr>
      </tbody>
   </table>
</form>

Notice that the name attribute `oooops_options[]` is capable of saving all values in the field. Another thing is oooops_get_option()is a function that will handle to get array value from database.

Getting Array Values from the WordPress Database




<?php
/**
* Getting values WP Options (Database)
*
* @param string $key_option It's a get_option key
* @param int|string|mixed $default_value Default value when empty
* @param int $index Position of indexes
* @return array $output
*
*/
function oooops_get_option($key_option = false, $default_value = '', $index = NULL){
$output = false;
if(empty($key_option)) return $output;
// check if it has default value
if(!empty($default_value)){
$output = $default_value;
}
// Just get value from database when no indexes
if($index === NULL && !empty( get_option($key_option) )){
$output = get_option($key_option);
return $output;
}
// If there is indexes
if($index !== NULL && !empty( get_option($key_option)[$index] )){
$output = get_option($key_option)[$index];
}
return $output;
}
?>

Of course, upon submission it needs a little tweak to handle $POST request. See the code below:

POST Request Handler for Array Values in WordPress

<?php
// $_POST needs to be sanitized
if( isset($_POST['submit'])
&& check_admin_referer('oooops_option_action','oooops_option_field') // @see WP Docs for check_admin_referer()
){
/** Array DB $options; if emtpy assign empty string */
$options = array(
'oooops_options' = isset($_POST["oooops_options"]) ? $_POST["oooops_options"]  : array(),
);
/* Handling var Array */
foreach($options as $option_name =&amp;amp;gt; $option_value) {
// If option name exist, update it; else add it!
if ( get_option( $option_name ) !== false ) {
update_option($option_name, $option_value);
} else {
add_option( $option_name, $option_value, '', 'yes');
}
}
}

On my personal note, I find it practical and flexible way to manage data in the WordPress Database. Also I would gladly hear your suggestions for the better coding. Enjoy!

A Clean Way to Display get_option in WordPress

Getting values from database using WordPress Hook function might be troublesome. You have to create a fallback statement in case unexpected values or output occurs. When you read its official get_option documentation you might come up for the solution of putting a default value when the option key has no corresponding value e.g. get_option('your-field-key', 'your-field-value'). Misconceptions on doing that is that, when option key exist and has no value, it actually returns nothing.

So the safer way to solve get_option() output, let’s create a function sanitizing the get_option results.

/**
 * Get Options Fixes
 * @param $db_field string
 * @param $default string
 */
function cool_option($db_field, $default){
  $get_option = get_option($db_field);
  // if it is empty string, 0, or null, just return the default value.
  if(empty($get_option)){
    $get_option = $default;
  }
  return $get_option;
}

Then when you echo that value, you can just call a one line of code

echo cool_option('your_wp_field_key', 'your default value');

I hope you could learn from this piece of code, just comment below for more clarification, enjoy coding!