• Resolved danieltj

    (@danieltj)


    Hi,

    I’m trying to make a plugin which has settings on a custom page within the WordPress admin area but it’s not working at all.

    I have a new page located at admin.php?page=CustomPlugin.

    Then, in a function I have the following:

    add_option('abc_plugin', '0');
    register_setting('abc_plugin_group', 'abc_plugin');

    Which is working because it’s adding the settings to the database which is fine. However when I go to my page, I edit the fields and save but non of the options are being updated.

    I’ve got the following functions in my template:

    <form method="post" name="core-settings">
    <?php settings_fields('abc_plugin_group');
    do_settings_sections('abc_plugin_group'); ?>
    
    [...]
    
    <?php submit_button(); ?>
    
    </form>

    What am I doing wrong here?

    Do I need to use add_settings_section() and add_settings_field() because I’ve checked other plugins and they don’t seem to use these functions because they’re on special, custom plugin pages.

    Please help!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Yes, you do need to add settings sections and fields, especially if you want do_settings_sections() to output your fields on your settings screen. If you don’t want to use sections, you can just add the fields and call do_settings_fields(). I don’t use the Settings API myself very much, so I may be misremembering. I think register_setting() is intended for adding individual settings to existing admin screens, like Settings > General for example. It’s the fields and sections you want to use for your own admin screens.

    Be sure you make API function calls from within a callback hooked to ‘admin_init’. If you haven’t seen it yet, review the Settings API in the Plugin Handbook.

    You are not going to want to use this line without a conditional: add_option('abc_plugin', '0'); As it is, this will reset the value stored to 0 on every request. Even if properly saved when you click “Submit”, on the very next request that line will reset it back to 0 again. It’s reasonable to want to assign an initial value, that is best done from your plugin activation hook. Or at least first try getting the value and only set it to 0 if nothing is returned.

    Thread Starter danieltj

    (@danieltj)

    Thanks for your reply! It turns out there were two things wrong which I needed to fix. The first was that I needed to use the settings field and section functions but I also needed to add action="options.php" to the form tag to make sure the data was passed on correctly even though my plugin pages are on admin.php.

    Moderator bcworkz

    (@bcworkz)

    You’re welcome. Good catch on options.php! I’m afraid I didn’t even look at that aspect. Teamwork FTW!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Plugin – Custom settings won’t save’ is closed to new replies.