I have an options page which is not added under the "settings" section, but via add_menu_page()/add_submenu_page()

This page contains of html markup for my settings and at the end

<div class="wrap">

<h1><div class="dashicons dashicons-hammer" style="font-size:30px;width:30px;height:30px;"></div> Options</h1>

<div class="meta_inner_admin">

    <?php settings_errors(); ?>

<form name="form_settings" id="form_settings" action="options.php" method="post">
            // generates the hidden fields for the settings and automatically adds a nonce
            submit_button( "Save Settings" );



I have written a function to validate one of the settings fields (its a simple input field and should contain small letters and an "-" only), the function is mapped to the sanitize callback

register_setting('plugin_settings', 'plugin_api_key', array( 'type' => 'string', 'sanitize_callback' => 'plugin_settings_validate_apikey', 'default' => 'change this initial api key' ) );

And here is the validation function

function plugin_settings_validate_apikey( $input ) {
    // need to verify the nonce, otherwise the input field is always empty
    wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'plugin_settings-options' );
    $old_option = get_option( 'plugin_api_key' );
    $ret = false;
    if (!$ret) {
        $input['plugin_api_key'] = $old_option;
        add_settings_error( 'plugin_api_key', 'plugin_api_key_error', 'The apikey is invalid', 'error');
    return $input;
    // returning input

Here the value of $ret should call the actual validation function which either returns true or false (but thats not the issue here).

I have two issues:

  1. If i add a settings error using add_settings_error() with the type of 'error', it is simply not shown if the form is saved (the callback function is run however, i checked that). I only get the default 'settings saved' display on top.
  2. If I save the form, the value of the input field is always empty after the page refreshes.

I don't know what causes that issues. I also tried hooking the settings_errors() instead of calling it in the html, but this also didn't work

function plugin_settings_add_errors() {
    wp_verify_nonce( sanitize_key( $_POST['_wpnonce'] ), 'plugin_settings-options' );
add_action( 'admin_notices', 'plugin_settings_add_errors' );

Best, Thomas

Your Answer

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

Browse other questions tagged or ask your own question.