1

I'm updating some code in one of my WordPress plugins by adding a nonce to improve security. The plugin that has a form that generates some output that the user can copy and paste as a shortcode. At the bottom of the settings form I have a second form that resets the first form to its defaults.

As the headline says, the nonce keeps failing.

<?php
/**
 * Form reset.
 *
 * @package Foobar/foobar
 */

// $parent and $token construct the page slug. Settings form and these variables omitted for clarity.

$html  = '<form id="my-reset" name="my-reset" method="post" action="options-general.php?page=' . $this->parent->token . '&tab=generator">';
$html .= wp_nonce_field( 'options-general.php?page=' . $this->parent->token . '&tab=generator', 'my_reset_nonce' );
$html .= '
  <p class="submit"><input name="reset" class="button button-secondary" type="submit" value="' . esc_html__( 'Reset the Shortcode Generator', 'textdomain' ) . '" >
        <input type="hidden" name="action" value="reset" />
    </p>
</form>';

if ( isset( $_POST['reset'] ) ) {
    if ( ! wp_verify_nonce( 'options-general.php?page=' . $this->parent->token . '&tab=generator', 'my_reset_nonce' ) ) {
        die( esc_html__( 'Invalid nonce. Form submission blocked!', 'textdomain' ) );
    } else {
        // Logic to reset the settings form.
    }
};

Any help appreciated.

2
0

Okay, not sure what was wrong with my original code, but this post put me on the right path.

To generate the nonce, use:

wp_nonce_field( plugin_basename( __FILE__ ), 'my_reset_nonce',true,false);

To verify, use:

if ( ! isset( $_POST['my_reset_nonce'] ) || ! wp_verify_nonce( ( $_POST['my_reset_nonce'] ), plugin_basename( __FILE__ ) ) ) {
    die;
} else {
    // Reset the form.
}

Various other variables, conditionals, sanitizing, etc. omitted for clarity.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.