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.


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.

| improve this answer | |

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.