1

I’m trying to add some options to my plugin but can’t understand why use add_settings_section when you could just use register_setting?

I’m registering my settings page via add_menu_page like so:

 add_menu_page(
        __( 'My plugin' ),
        __('My plugin'),
        'manage_options',
        'my_plugin_page_slug',
        'render'
);


//renders the page
function render () { ?>
     <div class="wrap">
     <form action="options.php" method="post">
         <?php
            settings_fields( 'my-awesome-plugin-settings' );
            do_settings_sections( 'my-awesome-plugin-settings' );
         ?>

     //render settings 

     <h2>Section title</h2>
            <div class="form__section">
                <input type="checkbox" name="setting_1" value="1" <?php checked(1, get_option('setting_1'), true); ?> />
                <label><?php _e('Label example') ?></label>
            </div>
     <!-- more settings here --> 

     <?php submit_button(); ?>

     </form>
     </div>
<?php }

Then I’m adding settings like so:

function register_my_cool_plugin_settings() {
     //register our settings
     register_setting( 'my-awesome-plugin-settings', 'setting_1' );
     ....
}

And it seems to work just fine.

What are benefits to use add_settings_section vs this approach?

1

One point which is probably less important, is that you do not need to worry about styling of headers and labels, as the settings API will take care of it.

The more important aspect is software design. The more options you have the less maintainable your code will become if you just write it in one function, and you will actually want to split it into smaller functions to make it more readable, and being able to have unit tests that test it. Since you get all of that "for free" when you use the settings API, you should have a good justification for not using it (maybe you want something that do not look at all like a usual admin page).

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.