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'); ?>
   <table class="form-table">
      <tbody>
      </tbody>
   </table>
   <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

/**
   * 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

// $_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 => $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!

WP get_option: A Practical Guide Save Values to Database2.00/5 (40.00%) 8 votes
About

Elvin is one of the contributors of InnoveDesigns.com. He has been creating Wordpress Plugins, Magento Extensions, & Mobile Applications. If you find this article useful, please Follow him on .

Published under Web Development Guide, Wordpress