settings api - register_setting sanitize callback $input is null

admin2025-01-08  4

I am struggling to get my settings page to save my options. I've got it showing up correctly and it hits the sanitize function

    register_setting(
        'my_options', // Option group
        'my_settings', // Option name
        array($this, 'sanitize') // Sanitize
    );

When I run the debugger on the sanitize function, $input is null:

public function sanitize($input)
{
    $new_input = array();

    $new_input = $input;
    //Sanitize the input actually

    return $new_input;
}

The form itself is called like this:

<form id="my-admin-form" method="post" action="options.php">
    <!-- Submission Notices -->
    <div class="status-box notice notice-info" style="display: none;"></div>
    <?php
    settings_fields('my_options');
    do_settings_sections('my_section');
    submit_button();
    ?>
</form>

I am struggling to get my settings page to save my options. I've got it showing up correctly and it hits the sanitize function

    register_setting(
        'my_options', // Option group
        'my_settings', // Option name
        array($this, 'sanitize') // Sanitize
    );

When I run the debugger on the sanitize function, $input is null:

public function sanitize($input)
{
    $new_input = array();

    $new_input = $input;
    //Sanitize the input actually

    return $new_input;
}

The form itself is called like this:

<form id="my-admin-form" method="post" action="options.php">
    <!-- Submission Notices -->
    <div class="status-box notice notice-info" style="display: none;"></div>
    <?php
    settings_fields('my_options');
    do_settings_sections('my_section');
    submit_button();
    ?>
</form>
Share Improve this question edited Jul 5, 2016 at 14:25 dhuyvetter asked Jul 5, 2016 at 14:01 dhuyvetterdhuyvetter 2073 silver badges12 bronze badges 3
  • Were you able to find the answer? – Vaviloff Commented Oct 18, 2016 at 13:11
  • I think I did, but I'm not sure any more and forgot which project this was in, so can't look it up. – dhuyvetter Commented Oct 19, 2016 at 10:24
  • 1 It might have been a nonce issue, where I was checking against a nonce that wasn't created. codex.wordpress.org/WordPress_Nonces – dhuyvetter Commented Oct 19, 2016 at 10:27
Add a comment  | 

2 Answers 2

Reset to default 2

It turned out to be nonce related: the form didn't have a nonce. Solved this by adding wp_nonce_field to the form.

I had a similar problem even after I added the nonce.

The mistake I'd made was that the input names need to be an array, for example:

<input id="my_option[key]" type="text" name="my_option[key]" value="<?php !empty(my_option[key]) ? my_option[key] : NULL; ?>">
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736268653a1291.html

最新回复(0)