Add section (add_settings_section) to a custom page (add_submenu_page)

The add_settings_section() function simply registers a form section with a certain slug with WordPress. In order to get the section and all the fields you’ve added to it to display on a certain menu page, you need to include the do_settings_sections($sections-slug) method in the menu’s callback. This is, of course, assuming you are using the Settings API, which add_settings_section is part of.

Example:

function plugin_admin_init() {
     //All callbacks must be valid names of functions, even if provided functions are blank
     register_setting( 'option_group', 'option_name', 'sanitize_callback' );
     add_settings_section( 'section_id', 'section_title', 'section_callback', 'section_page_type' );
     add_settings_field( 'field_id', 'field_title', 'field_callback', 'section_page_type', 'section_id' );
}
add_action( 'admin_init', 'plugin_admin_init' );

function add_menus() {
     add_menu_page( 'menu_page_title', 'menu_title', 'menu_capability', 'menu_slug', 'menu_callback');
     add_submenu_page( 'menu_slug', 'submenu_page_title', 'submenu_title', 'submenu_capability', 'submenu_slug', 'submenu_callback' );
}
add_action( 'admin_menu', 'add_menus' );

function submenu_callback() {
     ?>
     <div class="wrap">
          <h2>Settings</h2>
          <form method='post' action='options.php'>
          <?php 
               /* 'option_group' must match 'option_group' from register_setting call */
               settings_fields( 'option_group' );
               do_settings_sections( 'section_page_type' );
          ?>
               <p class="submit">
                    <input name="submit" type="submit" id='submit' class="button-primary" value="<?php _e("Save Changes") ?>" />
               </p>
          </form>
     </div>
     <?php
}

I did my best to keep all the parameter names unique, so you should be able to pick them apart and trace where they go. The Settings API gets very specific about what needs to go where, so make sure you have that all right. Also, keep in mind that I omitted all the callback functions from this example, but in reality they are necessary.

Leave a Comment