When should I call add_settings_section and add_settings_field?

All of the examples I’ve seen for add_settings_section & add_settings_field have them being called on the admin_init action. This means that they’re being called when loading every single admin page.

However, my understanding is that they’re only used when rendering the options page on which they’re displayed. Is there any reason no to put all calls to add_settings_section & add_settings_field in the callback function given to add_menu_page?

I’m wondering because I’ve got a plugin where the selection of fields to display is determined by a call to an external API. I certainly don’t want to have to do this on every admin page load. Even if I cache the result of the API call in a transient that’s going to expire every so often.

1 Answer
1

You can call add_settings_section and add_settings_field any time before you do_settings_sections:

add_action( 'my_plugin_add_settings_sections', function() {
    wp_remote_get( ... );
    add_settings_section( ... );
    add_settings_field( ... );
});

// On the plugin settings page output
do_action( 'my_plugin_add_settings_sections' );
do_settings_sections( ... );

You’ll still want to register_setting() earlier though because that custom hook won’t be fired when your settings are saved, so you want to make sure sanitize callback is in place, probably admin_init.

Leave a Comment