Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

php - Show custom error messages from wp plugin form submit

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.

question from:https://stackoverflow.com/questions/65909178/show-custom-error-messages-from-wp-plugin-form-submit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...