Show custom error messages from wp plugin form submit

Viewed 312

I am developing a WordPress plugin and pretty new to WordPress I am looking for a way to show custom error messages based on some logic in the plugin settings page in wp-admin

I have this form being shown in the wp-admin

<form method="post" action="options.php" autocomplete="off">
                    <?php
                    // This prints out all hidden setting fields
                    settings_fields('iskills_pros_and_cons');

                    // output setting sections based on tab selections
                    if ($active_tab == 'global') {
                        do_settings_sections('iskills_pros_and_cons_default');
                    } else if ($active_tab == 'heading') {
                        do_settings_sections('iskills_pros_and_cons_heading');
                    } else if ($active_tab == 'section') {
                        do_settings_sections('iskills_pros_and_cons_body');
                    } else if ($active_tab == 'button') {
                        do_settings_sections('iskills_pros_and_cons_button');
                    } else {
                        do_settings_sections('iskills_pros_and_cons_icons');
                    }

                    submit_button();
                    ?>
                </form>

I want on the form submission, I can check the active tab and if the active tab is global then perform some checks if these checks are failed then I want to send errors back to the same setting page. Can anyone guide me what is the better way to achieve this in WordPress? any help in this regard will highly be appreciated.

1 Answers

I used the sanitize method to make the custom validation, in case of failure returned an error

public function sanitize($input) {
        if(true) {
            // There is an error
            add_settings_error( 'general', 'settings_updated', __( "Message" ), 'error' );
            set_transient( 'settings_errors', get_settings_errors(), 30 );
            // Redirect back to the settings page that was submitted.
            $goback = add_query_arg( 'settings-updated', 'true', wp_get_referer() );
            wp_redirect( $goback );
            exit;
        }
    }
Related