How to use settings API and print custom validation errors (3 posts)

  1. loothi
    Posted 5 years ago #

    Hi there,
    Can anyone point me in the direction of an example where the Settings API has been used AND specific validation errors are printed in response to a plugin's settings page?

    ie "This is not a valid email" or "No such file"

    It appears more sensible to use the Settings API and options.php but I can't see how to add my own error messages.


  2. Gwyneth Llewelyn
    Posted 5 years ago #

    It's not easy. Apparently that functionality is not built-in (yet) on the settings API.

    Two hacks that allow that are somewhat explained here:


    One involves having an extra hidden field that gets rewritten with the error message; the other, more complex to figure out, but probably cleaner, involves adding a admin_notices hook.

    I haven't tried them myself, but hopefully they're useful. I'm looking for a cleaner way to do that myself.

  3. keesiemeijer
    Posted 5 years ago #

    I was trying this also and this worked for me:

    add_action( 'admin_notices', 'my_validation_notice');
      function my_validation_notice(){
        global $pagenow;
        if ($pagenow == 'options-general.php' && $_GET['page'] ==
    'my-plugin') { // change my-plugin to your plugin page
          if ( (isset($_GET['updated']) && $_GET['updated'] == 'true') || (isset($_GET['settings-updated']) && $_GET['settings-updated'] == 'true') ) {
          //this will clear the update message "Settings Saved" totally
          //get_settings_errors() also will clear the update message
          $errors = get_settings_errors();
          /* get_settings_errors() returns an array With the original message
    [0] => Array
                [setting] => general
                [code] => settings_updated
                [message] => Settings saved.
                [type] => updated
          // add your own messages or add the original message back 
          // original message
          $original_message = $errors[0]['message'];
    ', 'settings_updated', $original_message, 'updated');
          // your messages
          $error_message = 'my error message';
    ', 'settings_updated', $error_message, 'error');
          $update_message = 'my update message';
    ', 'settings_updated', $update_message, 'updated');

    Thanks for the link Gwyneth Llewelyn. There is not much information out there on Setting Api validation and Admin page notices.

Topic Closed

This topic has been closed to new replies.

About this Topic