1

Currently I do:

$options = get_option( 'jons-plugin-options' );
        echo "<input id='jons-plugin-options[field-two]' name='jons-plugin-options[field-two]' size='4' type='text' value='" . $options['field-two'] . "' />";

But it does not get the submitted form value and display it when I do:

add_settings_error( 'field-two', 'field-two', 'Field two must not be 0.' );
return false;

In the register_setting callback.

0

You can't. If you're using the settings API correctly, here's what happens when you try to save your options:

  1. Form posts to options.php
  2. WordPress handles $_POST and runs update_option on your registered settings
  3. Your sanitize callback from register_setting is applied
  4. Any data that fails/you don't return in your callback isn't saved
  5. WordPress redirects back to your options page (GET)

Now you're back on your options page, with the error message, but the data wasn't written to the database and now $_POST will be empty.

The only way I can see around it is to store the "incorrect" data in another option, inside your sanitize callback, for use on the returned page.

0

here is how I handled the problem. Hope it might help someone.

/**
 * Add a validation callback to the settings form
 */
public function options_update()
{
    register_setting($this->plugin_name, $this->plugin_name, array($this, 'validate'));
}

/**
 * Validates and sanitizes the submitted values
 * @param $input
 * @return array
 */
public function validate($input)
{
    $valid = array();

    $valid['is_api_enabled'] = (isset($input['is_api_enabled']) && !empty($input['is_api_enabled'])) ? 1 : 0;
    $valid['api_key'] = (isset($input['api_key'])) ? $input['api_key'] : '';

    if ($valid['is_api_enabled'] === 1) {
        if (!$valid['api_key'] || empty(trim($valid['api_key']))) {
            add_settings_error($this->plugin_name, 'api_key', __('API key is mandatory if API is enabled'));

            $this->revert_setting($valid, $this->plugin_name, 'api_key');
            $this->revert_setting($valid, $this->plugin_name, 'is_api_enabled');
        }
    }

    // only return accepted values (old ones or correct)
    return $valid;
}

/**
 * Revert the submitted setting to its original value
 * @param $new
 * @param $option
 * @param null $key
 */
private function revert_setting(&$new, $option, $key = null)
{
    $old = get_option($option);

    if ($key) {
        $new[$key] = array_key_exists($key, $old) ? $old[$key] : null;
    } else {
        $new = $old;
    }
}

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.