Home > Net >  How to perform an operation after submitting a form in WP plugin settings
How to perform an operation after submitting a form in WP plugin settings

Time:12-23

I am creating a WordPress plugin and I have added a form to the plugin's Settings page. I want to perform a specific operation after the form is submitted and the "Save Changes" button is clicked.

I have tried using the isset() function and other ways, but none of them seem to be working.

Here is the code for my form:

<div >
    <div id="icon-themes" ></div>
    <h2>My Settings</h2>
    <?php settings_errors();
    if (isset($_POST['form_submitted'])) {
        echo '<script>alert("Hello World")</script>';
    } ?>
    <form method="POST" action="options.php">
        <?php
        settings_fields('my_general_settings');
        do_settings_sections('my_general_settings');
        ?>
        <?php submit_button(); ?>
        <input type="hidden" name="form_submitted" value="1">
    </form>
</div>

What would be the correct way to perform an action after the form is submitted and the "Save Changes" button is clicked? Is there a built-in hook that can be used for this? Or perhaps something like this: isset( $_GET[ 'settings-updated' ] ?

CodePudding user response:

You can try using the "admin_init" hook. This hook is called after WordPress has finished loading but before any headers are sent.

function your_plugin_settings_init() {
    // This is checking if your form is submitted
    if (isset($_POST['form_submitted'])) {
        // perform your specific operation here
        echo '<script>alert("Hello World")</script>';
    }
}
add_action('admin_init', 'your_plugin_settings_init');
  • Related