Give feedback on errors with the WordPress Settings API


Share

After working with the WordPress Settings API I first found no easy way out to give feedback on errors.

As a lot of you I was reading the tutorials from David Gwyer, Ozh, BobGneu and Otto, but none of them gave proper information on how to pass the error messages to the user when theie values fail the validation test.

BUT…. I found a somehow quick but practicable way to bypass the lack of user validation information.

Take the sanitize function you call from register_setting which is responsible to check the values:


<?php

function myplugin_options_validate($input) {

// use  $input['error'] and $input['message'] for error messages

$input['error'] = false;

$input['message'] = '';

# do some regex validation

if (1=!1) { // yes we have an error

$input['error'] = true;

$input['message'] = 'you have got an error: 1!=1';

}

return $input;

}

?>

Now go to the function which creates the settings form (most called via add_options_page) and check with $_GET['settings-updated'].


<?php

function myplugin_options_page() {

if ($_GET['settings-updated'])  { // yes, settings have been changed

if ($_GET['settings-updated'] && $options['error']) {
print '<div>'.$options['message'].'</div>';
}

}

?>

That’s it.

2 Kommentare zu „Give feedback on errors with the WordPress Settings API“