WordPress Plugin Admin Menus & Settings API
Learning Objectives
By mastering this chapter, developers will be able to:
- Register custom top-level admin menu pages and sub-menu pages connected to the
admin_menuaction hook. - Configure menu access permissions using WordPress capability flags like
manage_options. - Assign custom icons using built-in WordPress Dashicons or custom asset URLs.
- Organize setting forms into structured sections and fields using the WordPress Settings API.
- Safely handle form submissions, automatic nonce verification, and settings sanitization using
settings_fields(),do_settings_sections(), andsubmit_button(). - Retrieve, store, and manipulate database options from the
wp_optionstable usingget_option()andupdate_option(). - Modularize administrative logic cleanly across specialized plugin files (
inc/admin-menu.php,inc/admin-settings.php,admin/views/admin-page.php) linked to the main plugin file (msr-plugin.php).
Key Concepts & Prerequisites
- Key Concepts: Top-Level Admin Menu, Sub-Menu Page, Access Capabilities, Menu Slug, Dashicons, Settings API, Options API (
wp_options), Form Sanitization Callback, Nonce Security,settings_fields,do_settings_sections. - Prerequisites: Action hooks and callbacks (
add_action) covered in Lecture 06, path and URL constants (plugin_dir_path,plugin_dir_url) from Lecture 05, and PHP form handling fundamentals.
Concept Explanation & Architectural Fundamentals
WordPress Administration Menus
In WordPress plugin development, providing an intuitive settings interface is essential for user management. WordPress organizes its administrative sidebar into Top-Level Menus (parent items appearing directly on the navigation sidebar) and Sub-Level Menus (child items nested inside parent menus or standard core menus like Settings, Tools, or Appearance).
WP-Admin Menu Architecture
├── Top-Level Menu (MSR Plugin) -> add_menu_page()
│ ├── Sub-Menu 1 (Dashboard) -> add_submenu_page()
│ └── Sub-Menu 2 (Settings) -> add_submenu_page()
└── Built-in Core Menus
├── Settings (options-general.php)
└── Tools (tools.php) -> add_submenu_page('tools.php', ...)
Why it is needed:
- Centralized Configuration: Provides a dedicated user interface where administrators can customize plugin behavior without editing PHP files.
- Role-Based Access Control: Ensures only authorized users (e.g., administrators with
manage_optionscapability) can view and modify plugin settings. - Modular Sub-Pages: Allows developers to split complex plugin functionality across multiple specialized tabs or sub-pages.
The WordPress Settings API vs. Options API
Creating custom administrative setting pages requires two complementary WordPress APIs:
- Settings API: Handles the generation, structuring, and security of administrative HTML forms. It registers settings, defines sections, renders input fields, and automatically injects security nonces into forms.
- Options API: Handles database persistence inside the
wp_optionstable. It provides simple key-value storage functions (get_option(),update_option(),add_option(),delete_option()).
Core Components of the Settings API:
- Setting (
register_setting()): Registers an option key in the database and binds it to a sanitization callback. - Setting Section (
add_settings_section()): Groups related settings fields together under a common header title and descriptive text. - Setting Field (
add_settings_field()): Binds an HTML form input control (text input, checkbox, select dropdown) to a registered setting.
Deep-Dive Code Explanation
Snippet 1: Registering Top-Level and Sub-Level Admin Menus
Line-by-Line Detailed Explanation:
if ( ! defined( 'ABSPATH' ) ) exit;: Prevents unauthorized direct file execution over HTTP.function msr_plugin_register_admin_menus() {: Declares the callback function responsible for registering all plugin admin menu items.add_menu_page(...): Registers a top-level menu item on the WP-Admin sidebar.- Parameter 1 (
'MSR Plugin Page Title'): The text rendered inside the browser title bar when viewing the page. - Parameter 2 (
'MSR Plugin'): The visible text label displayed on the sidebar menu link. - Parameter 3 (
'manage_options'): Minimum user capability required to see and access the menu page. - Parameter 4 (
'msr-plugin-settings'): Unique URL slug identifier (page=msr-plugin-settings). - Parameter 5 (
'msr_plugin_admin_page_html'): Callback function invoked to output page content HTML. - Parameter 6 (
'dashicons-superhero'): Dashicon class name for the sidebar menu icon. - Parameter 7 (
25): Menu position on the sidebar (25 places it below Comments and above Appearance).
- Parameter 1 (
add_submenu_page(...): Registers a sub-menu item.- When passing
'msr-plugin-settings'as the parent slug, it attaches the sub-menu under the custom top-level menu. - When passing
'tools.php'as the parent slug, it nests the sub-menu under the built-in WordPress Tools menu.
- When passing
add_action( 'admin_menu', 'msr_plugin_register_admin_menus' );: Hooks menu registration callback to theadmin_menuWordPress action hook.
Snippet 2: Registering Settings, Sections, and Fields
Line-by-Line Detailed Explanation:
register_setting(...): Registers a database option key undermsr_options_group. It specifiessanitize_text_fieldto automatically clean input strings prior to database insertion.add_settings_section(...): Defines a logical container section titled General Settings associated with the page slugmsr-plugin-settings.add_settings_field(...): Binds a text field tomsr_general_section. When rendered, WordPress callsmsr_text_field_render().add_action( 'admin_init', 'msr_plugin_settings_init' );: Hooks settings initialization toadmin_init(which executes before admin pages render).get_option( 'msr_setting_option_name', '' ): Fetches the current saved value from thewp_optionstable. If no value exists, it defaults to an empty string''.esc_attr( $value ): Escapes HTML attribute content to prevent XSS vulnerabilities when outputting values inside form fields.
Snippet 3: Rendering the Settings Page Form
Line-by-Line Detailed Explanation:
current_user_can( 'manage_options' ): Verifies that the current logged-in user possesses administrative permissions before rendering the form.settings_errors(...): Renders standard WordPress admin notice alerts (e.g., green success banners when settings are updated).<form action="options.php" method="post">: All Settings API forms must submit viaPOSTto the coreoptions.phpform handler endpoint.settings_fields( 'msr_options_group' ): Outputs required hidden security fields including CSRF nonces and option page identifiers.do_settings_sections( 'msr-plugin-settings' ): Iterates through all sections and fields registered formsr-plugin-settingsand prints their HTML table structure.submit_button( 'Save Plugin Settings' ): Generates a standard, styled WordPress primary submit button (<input type="submit" ...>).
WordPress Technical Reference Guide
Essential Action Hooks for Admin Interfaces
| Hook Name | Target Environment | Execution Context & Stage | Recommended Usage |
|---|---|---|---|
admin_menu | WP-Admin Sidebar | Fires when building the main administrative navigation menu structure. | Register top-level menus (add_menu_page) and sub-menus (add_submenu_page). |
admin_init | WP-Admin Bootstrapper | Fires before any admin screen is rendered, after user authentication. | Register settings (register_setting), add sections (add_settings_section), and define fields. |
network_admin_menu | Multisite Network Admin | Fires when building navigation menus for Multisite Network Super Admins. | Add network-wide plugin configuration screens. |
Core Admin Menu Functions
| Function Name | Return Type | Key Arguments | Purpose & Rules |
|---|---|---|---|
add_menu_page() | string | $page_title, $menu_title, $capability, $menu_slug, $callback, $icon_url, $position | Registers a top-level menu item on the WP-Admin sidebar. |
add_submenu_page() | `string\ | false` | $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $callback, $position |
remove_menu_page() | `array\ | false` | $menu_slug |
remove_submenu_page() | `array\ | false` | $menu_slug, $submenu_slug |
Core Settings API Functions
| Function Name | Parameters | Purpose | Required Execution Hook |
|---|---|---|---|
register_setting() | $option_group, $option_name, $args | Registers a setting key in wp_options with type and sanitization rules. | admin_init |
add_settings_section() | $id, $title, $callback, $page | Registers a visual group container for setting fields on a page. | admin_init |
add_settings_field() | $id, $title, $callback, $page, $section, $args | Binds an HTML input control to a specific setting section. | admin_init |
settings_fields() | $option_group | Outputs hidden security nonces, option group IDs, and referrer fields inside <form>. | Render Callback (Inside <form>) |
do_settings_sections() | $page | Outputs all registered sections and their associated input fields for a page. | Render Callback (Inside <form>) |
submit_button() | $text, $type, $name, $wrap, $other_attributes | Renders a standard WordPress-styled submit button. | Render Callback (Inside <form>) |
Core Options API Functions
| Function Name | Return Type | Key Parameters | Purpose & Rules |
|---|---|---|---|
get_option() | mixed | $option_name, $default = false | Retrieves an option value from wp_options. Returns $default if key doesn’t exist. |
update_option() | bool | $option_name, $value, $autoload = null | Updates an option in wp_options. Creates option if it does not already exist. |
add_option() | bool | $option_name, $value, $deprecated = '', $autoload = 'yes' | Adds a new option to wp_options. Does nothing if option already exists. |
delete_option() | bool | $option_name | Permanently deletes an option row from wp_options. |
Practical Step-by-Step Plugin Implementation Guide
Follow these steps to build and verify a complete Admin Menu and Settings API implementation locally.
Step 1: Create Plugin Directory & Modular Files
Inside your local WordPress installation (wp-content/plugins/), create a directory named msr-settings-demo and add the following subdirectories and files:
mkdir -p msr-settings-demo/inc msr-settings-demo/admin/views
Step 2: Create Main Bootstrapper
Create msr-settings-demo/msr-settings-demo.php and paste the following code:
<?php
/**
* Plugin Name: MSR Settings API Demo
* Description: Modular admin menu and Settings API implementation.
* Version: 1.0.0
* Author: CSE Study247
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'MSR_DEMO_PATH', plugin_dir_path( __FILE__ ) );
define( 'MSR_DEMO_URL', plugin_dir_url( __FILE__ ) );
// Include Modular Architecture Files
require_once MSR_DEMO_PATH . 'inc/admin-menu.php';
require_once MSR_DEMO_PATH . 'inc/admin-settings.php';
Step 3: Implement Menu Registration
Create msr-settings-demo/inc/admin-menu.php and add:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function msr_demo_register_menus() {
add_menu_page(
'MSR Settings Demo',
'MSR Demo',
'manage_options',
'msr-demo-settings',
'msr_demo_render_settings_page',
'dashicons-admin-generic',
30
);
}
add_action( 'admin_menu', 'msr_demo_register_menus' );
function msr_demo_render_settings_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
?>
<div class="wrap">
<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
<form action="options.php" method="post">
<?php
settings_fields( 'msr_demo_option_group' );
do_settings_sections( 'msr-demo-settings' );
submit_button( 'Save Changes' );
?>
</form>
</div>
<?php
}
Step 4: Implement Settings API Logic
Create msr-settings-demo/inc/admin-settings.php and add:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function msr_demo_settings_init() {
register_setting(
'msr_demo_option_group',
'msr_demo_api_key',
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
)
);
add_settings_section(
'msr_demo_main_section',
'API Configuration',
'msr_demo_section_callback',
'msr-demo-settings'
);
add_settings_field(
'msr_demo_api_key_field',
'License / API Key',
'msr_demo_api_key_render',
'msr-demo-settings',
'msr_demo_main_section'
);
}
add_action( 'admin_init', 'msr_demo_settings_init' );
function msr_demo_section_callback() {
echo '<p>Enter your API authorization credentials below.</p>';
}
function msr_demo_api_key_render() {
$api_key = get_option( 'msr_demo_api_key', '' );
echo '<input type="text" name="msr_demo_api_key" value="' . esc_attr( $api_key ) . '" class="regular-text" placeholder="e.g. key_live_123456">';
}
Step 5: Activate and Test
- Navigate to WP-Admin -> Plugins and click Activate on MSR Settings API Demo.
- Notice the new sidebar menu item named MSR Demo with a gear icon.
- Click MSR Demo, enter
key_live_987654321into the text box, and click Save Changes. - Verify that a green success banner appears (“Settings saved”) and the saved value persists after page refresh.
Common Pitfalls, Security Vulnerabilities & Best Practices
Critical Pitfalls & Solutions
1. Form Action Pointing to Wrong Endpoint
- The Error: Setting
<form action="">or pointing to a custom page instead ofoptions.php. - Symptom: Form submits, but settings fail to save in
wp_options, or user is redirected to a 404 page. - Fix: Always set the form action explicitly to
options.php:<form action="options.php" method="post">.
2. Option Group Mismatch
- The Error: Passing one string to
register_setting('group_a', ...)and a different string tosettings_fields('group_b'). - Symptom: Submitting the form triggers a security error:
"options.php: error processing form"or"uneditable option". - Fix: Ensure the
$option_groupparameter inregister_setting()exactly matches the string passed tosettings_fields().
3. Unsanitized Option Inputs
- The Error: Registering options without a
sanitize_callback. - Symptom: Attackers can submit raw HTML/JavaScript code (
<script>alert('xss')</script>) into input fields, causing Stored Cross-Site Scripting (XSS) vulnerabilities inside WP-Admin. - Fix: Always specify a sanitization callback such as
sanitize_text_field,absint,sanitize_email, or a custom validation callback insideregister_setting().
4. Hardcoding HTML Without Capability Checks
- The Error: Omitting capability verification inside admin page render callbacks.
- Symptom: Lower-privileged users (e.g., Subscribers or Contributors) who guess administrative URL slugs can view sensitive settings UI.
- Fix: Wrap all render callback logic in capability checks using
current_user_can( 'manage_options' ).
Cumulative Technical Interview Preparation (25 Questions)
Q1: Which WordPress action hook must be used to register administrative menu pages?
- Answer:
admin_menu. - Follow-Up Question: What hook is used to register Settings API configurations?
- Answer:
admin_init.
- Answer:
Q2: What is the purpose of the $capability parameter in add_menu_page()?
- Answer: It defines the minimum user permission (e.g.,
manage_options) required for a user to see and access the menu page in WP-Admin. - Follow-Up Question: What happens if a user without that capability attempts to navigate to the menu URL directly?
- Answer: WordPress displays an “Sorry, you are not allowed to access this page” error screen (HTTP 403 Forbidden).
Q3: What database table stores option data created by register_setting()?
- Answer: The
wp_optionstable. - Follow-Up Question: How can you inspect saved options directly in PHP?
- Answer: Using
get_option( 'option_name' ).
- Answer: Using
Q4: Why must Settings API forms submit to options.php?
- Answer:
options.phpis WordPress core’s dedicated form processing handler that automatically verifies CSRF nonces, checks user capabilities, executes sanitization callbacks, and updates database options. - Follow-Up Question: Can you submit settings forms via AJAX instead of
options.php?- Answer: Yes, by creating custom
wp_ajax_callbacks that executeupdate_option()after validating nonces manually.
- Answer: Yes, by creating custom
Q5: What function renders hidden security fields and nonces inside a Settings API form?
- Answer:
settings_fields( $option_group ). - Follow-Up Question: What happens if
settings_fields()is omitted from a form?- Answer: Form submission to
options.phpwill fail security verification and trigger an “Invalid nonce” error.
- Answer: Form submission to
Intermediate Questions
Q6: What is the difference between add_menu_page() and add_submenu_page()?
- Answer:
add_menu_page()creates a main top-level menu item on the WP-Admin sidebar.add_submenu_page()attaches a child menu item under an existing top-level parent menu (or core menus likeoptions-general.php,tools.php). - Follow-Up Question: How do you add a sub-menu under the core “Settings” menu specifically?
- Answer: Pass
'options-general.php'as the$parent_slugparameter ofadd_submenu_page()(or useadd_options_page()).
- Answer: Pass
Q7: How does do_settings_sections( $page_slug ) know which sections and fields to display?
- Answer: It checks WordPress internal global arrays for all sections added via
add_settings_section()and fields added viaadd_settings_field()matching the specified$page_slug. - Follow-Up Question: What happens if a section has no fields attached to it?
- Answer: WordPress renders the section title and description callback output, but no input fields or table rows.
Q8: What is the function of the sanitize_callback argument in register_setting()?
- Answer: It defines a callable function that intercepts raw user input submitted via POST, cleans or validates it, and returns the sanitized value to be written to
wp_options. - Follow-Up Question: What built-in WordPress sanitization function should be used for plain text strings?
- Answer:
sanitize_text_field().
- Answer:
Q9: How can you change the default position of a top-level admin menu?
- Answer: By supplying a numeric priority integer to the
$positionparameter ofadd_menu_page(). For example,2places it near Dashboard,25near Comments,75near Users, and80near Settings. - Follow-Up Question: What is the risk of using integers already assigned to core menus?
- Answer: Menu collisions may cause items to overlap or shift unexpectedly depending on active plugins.
Q10: What is the purpose of settings_errors()?
- Answer: It outputs administrative update notices and error messages generated during settings processing (e.g., “Settings saved” or custom validation error messages added via
add_settings_error()). - Follow-Up Question: On which screen should
settings_errors()be called?- Answer: Inside the administrative page render callback above the form HTML.
Advanced Questions
Q11: How do you register settings for an array of multiple input values under a single database option key?
- Answer: Register a single option key in
register_setting()(e.g.,my_plugin_options). In input field render callbacks, format field name attributes using array notation:name="my_plugin_options[api_key]"andname="my_plugin_options[enable_cache]". Pass a custom sanitization callback that iterates over the array elements. - Follow-Up Question: What is the architectural advantage of storing settings as a single array option versus individual options?
- Answer: Storing options in a single array reduces database queries by loading all plugin configuration in a single row fetch from
wp_options.
- Answer: Storing options in a single array reduces database queries by loading all plugin configuration in a single row fetch from
Q12: Explain how Dashicons are referenced in add_menu_page().
- Answer: Pass the Dashicon CSS class identifier string (e.g.,
'dashicons-chart-bar') as the$icon_urlparameter. Alternatively, pass a base64-encoded SVG string or a full HTTP URL pointing to a custom PNG/SVG image file. - Follow-Up Question: How do you hide a top-level menu icon entirely?
- Answer: Pass
'none'as the icon parameter and apply custom CSS viaadmin_enqueue_scripts.
- Answer: Pass
Q13: How can you dynamically display custom settings error messages if validation fails?
- Answer: Inside a custom
sanitize_callback, check if input criteria are met. If invalid, calladd_settings_error( $setting_name, $code, $message, $type = 'error' )and return the old or fallback option value. - Follow-Up Question: What does
$type = 'error'control?- Answer: It controls the admin notice styling class (red banner for
'error', yellow for'warning', green for'success').
- Answer: It controls the admin notice styling class (red banner for
Q14: How does get_option() handle autoloading, and why does autoload performance matter?
- Answer: When an option is created with
$autoload = 'yes'(the default inadd_option()andupdate_option()), WordPress loads it into memory automatically during core startup (alloptionsquery). Autoloading frequently used settings prevents extra database queries; however, storing massive objects with autoload enabled degrades site-wide performance. - Follow-Up Question: How do you disable autoloading for large option arrays?
- Answer: Set
$autoload = false(or'no') inadd_option()orupdate_option().
- Answer: Set
Q15: How can a developer remove a core WordPress admin menu item (e.g., “Comments”) programmatically?
- Answer: Call
remove_menu_page( 'edit-comments.php' )inside a callback hooked toadmin_menuwith a priority higher than default (e.g., priority999). - Follow-Up Question: Does removing a menu item revoke user access to that page?
- Answer: No,
remove_menu_page()only hides the sidebar link. Access control must still be enforced via capabilities.
- Answer: No,
Coding Questions
Q16: Write code to register a top-level admin menu named “Analytics” with a chart icon at position 50.
function register_analytics_menu() {
add_menu_page(
'Analytics Dashboard',
'Analytics',
'manage_options',
'analytics-dashboard',
'render_analytics_page',
'dashicons-chart-bar',
50
);
}
add_action( 'admin_menu', 'register_analytics_menu' );
Q17: Write code to register a setting my_plugin_email with email sanitization.
function register_email_setting() {
register_setting(
'my_plugin_options_group',
'my_plugin_email',
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_email',
'default' => '',
)
);
}
add_action( 'admin_init', 'register_email_setting' );
Q18: Correct the security and logic errors in the following form code:
Buggy Code:
<form action="my-page.php" method="get">
<input type="text" name="my_option" value="<?php echo get_option('my_option'); ?>">
<input type="submit">
</form>
Corrected Code:
<form action="options.php" method="post">
<?php
settings_fields( 'my_option_group' );
do_settings_sections( 'my-page-slug' );
submit_button();
?>
</form>
Explanation: Form action must point to options.php, method must be post, and settings_fields() must be present to include CSRF nonces. Inputs must be escaped with esc_attr().
Q19: Write a render callback for a checkbox setting named my_enable_feature.
function render_feature_checkbox() {
$value = get_option( 'my_enable_feature', '0' );
?>
<input type="checkbox" name="my_enable_feature" value="1" <?php checked( '1', $value ); ?>>
<span class="description">Check to enable advanced feature.</span>
<?php
}
Q20: Write code to add a sub-menu under the core “Settings” menu.
function register_custom_settings_submenu() {
add_options_page(
'Custom Submenu Settings',
'Custom Plugin',
'manage_options',
'custom-plugin-settings',
'render_custom_submenu_page'
);
}
add_action( 'admin_menu', 'register_custom_settings_submenu' );
Scenario-Based Questions
Q21: An administrator reports that saving a settings form displays a “You do not have sufficient permissions to access this page” error on submission. What is the most likely cause?
- Answer: Capability mismatch or missing option group registration. The
$option_groupstring passed tosettings_fields()in the form HTML does not match the$option_groupregistered inregister_setting(), causingoptions.phpto treat the submission as an unpermitted setting key.
Q22: You want your plugin options page to feature a modern UI with visual toggles and text inputs generated quickly without writing boilerplate Settings API code manually. What approach should you take?
- Answer: Build the setting page fields using visual generators (like the WP Magic Settings Generator tool demonstrated in Lecture 10) or utilize established admin UI frameworks (such as CMB2 or Codestar Framework), then integrate the generated code into modular plugin files.
Q23: A client requests that setting changes should display a custom notification (“API connection verified!”) when a valid API key is entered. How do you implement this?
- Answer: Inside the
sanitize_callbackfor the API key setting, perform an API validation check. If valid, calladd_settings_error( 'my_api_key', 'api_success', 'API connection verified!', 'updated' ). In the render callback, callsettings_errors( 'my_api_key' ).
Q24: You need to store multiple configuration settings (API URL, Timeout, Retry Count, Cache Status) for a high-traffic site. How should you structure database storage to optimize site speed?
- Answer: Combine all configuration fields into a single associative array stored under one option key (
my_plugin_config) inwp_options. Storing one array option loads all settings in a single SQL query during boot up rather than executing four separate queries.
Q25: A user installs your plugin on a WordPress Multisite network and wants setting changes to apply across all sites in the network. Will standard Settings API work?
- Answer: No. Standard Settings API saves options to individual site tables (
wp_options). For network-wide settings, register menu pages usingnetwork_admin_menu, process form submissions manually, and store network options inwp_sitemetausingget_site_option()andupdate_site_option().
Interactive Practice & Skill Assessment
Q1: Which hook must be used to execute add_menu_page()?
- A)
init - B)
admin_init - C)
admin_menu - D)
wp_loaded - Answer: C
- Explanation:
add_menu_page()must be hooked toadmin_menu.
Q2: What parameter of add_menu_page() defines the sidebar text label?
- A)
$page_title - B)
$menu_title - C)
$menu_slug - D)
$capability - Answer: B
- Explanation:
$menu_titlesets the visible link label on the admin sidebar.
Q3: Which hook must be used to register settings via register_setting()?
- A)
admin_menu - B)
admin_init - C)
wp_enqueue_scripts - D)
setup_theme - Answer: B
- Explanation:
register_setting()must be executed during theadmin_initaction hook.
Q4: What action URL must Settings API forms submit to?
- A)
admin-post.php - B)
options.php - C)
index.php - D)
wp-admin.php - Answer: B
- Explanation:
options.phpis core WordPress’s dedicated Settings API form processor.
Q5: What function outputs hidden security nonces and referrer fields in a settings form?
- A)
do_settings_sections() - B)
settings_errors() - C)
settings_fields() - D)
submit_button() - Answer: C
- Explanation:
settings_fields()outputs CSRF nonces and hidden option group fields.
Q6: Which function renders registered sections and their associated input fields?
- A)
do_settings_sections() - B)
add_settings_field() - C)
register_setting() - D)
settings_fields() - Answer: A
- Explanation:
do_settings_sections()outputs section titles, descriptions, and field tables.
Q7: Which function fetches an option value from the wp_options database table?
- A)
fetch_option() - B)
get_option() - C)
read_option() - D)
select_option() - Answer: B
- Explanation:
get_option( 'key' )retrieves saved values fromwp_options.
Q8: What WordPress helper function checks if a checkbox value matches a target string and outputs checked='checked'?
- A)
is_checked() - B)
checked() - C)
selected() - D)
verify_checked() - Answer: B
- Explanation:
checked( $value, $current )outputs the HTMLcheckedattribute if arguments match.
Q9: What built-in capability flag is standard for administrative settings access?
- A)
edit_posts - B)
read - C)
manage_options - D)
publish_pages - Answer: C
- Explanation:
manage_optionsis assigned to Administrators by default.
Q10: What function updates an existing option value in the database or creates it if absent?
- A)
save_option() - B)
update_option() - C)
put_option() - D)
set_option() - Answer: B
- Explanation:
update_option()handles option creation and updates automatically.
Hands-On Coding Exercises
Exercise 1: Register Top-Level Menu
Write code to register a top-level menu titled “Plugin Hub” with slug plugin-hub and icon dashicons-networking.
// Solution
function register_hub_menu() {
add_menu_page(
'Plugin Hub Page',
'Plugin Hub',
'manage_options',
'plugin-hub',
'render_hub_page',
'dashicons-networking',
20
);
}
add_action( 'admin_menu', 'register_hub_menu' );
Exercise 2: Register Text Setting
Write code to register a setting hub_license_key with text sanitization under group hub_options.
// Solution
function register_hub_settings() {
register_setting(
'hub_options',
'hub_license_key',
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
)
);
}
add_action( 'admin_init', 'register_hub_settings' );
Exercise 3: Section & Field Registration
Write code adding section hub_main_section and field hub_key_field to page plugin-hub.
// Solution
function setup_hub_sections() {
add_settings_section(
'hub_main_section',
'License Configuration',
'__return_false',
'plugin-hub'
);
add_settings_field(
'hub_key_field',
'License Key',
'render_hub_key_field',
'plugin-hub',
'hub_main_section'
);
}
add_action( 'admin_init', 'setup_hub_sections' );
Exercise 4: Render Settings Form
Write the render callback for plugin-hub outputting the Settings API form.
// Solution
function render_hub_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
?>
<div class="wrap">
<h1>Plugin Hub Settings</h1>
<form action="options.php" method="post">
<?php
settings_fields( 'hub_options' );
do_settings_sections( 'plugin-hub' );
submit_button();
?>
</form>
</div>
<?php
}
Exercise 5: Debugging Form Error
Fix the bug in the following render callback:
// BROKEN CODE
function render_my_page() {
echo '<form action="options-save.php" method="get">';
do_settings_sections('my-slug');
echo '</form>';
}
// CORRECTED CODE
function render_my_page() {
?>
<form action="options.php" method="post">
<?php
settings_fields( 'my_option_group' );
do_settings_sections( 'my-slug' );
submit_button();
?>
</form>
<?php
}
5-Minute Core Takeaways
- Admin Menus: Hook
add_menu_page()oradd_submenu_page()toadmin_menu. - Settings API: Hook
register_setting(),add_settings_section(), andadd_settings_field()toadmin_init. - Form Endpoint: Forms must use
<form action="options.php" method="post">. - Security: Form HTML must call
settings_fields( $group_name )to output CSRF nonces. - Rendering: Call
do_settings_sections( $page_slug )andsubmit_button(). - Persistence: Retrieve settings using
get_option( $option_name ).
Syntax & Code Cheatsheet
// 1. Menu Registration (admin_menu)
add_action( 'admin_menu', function() {
add_menu_page( 'Title', 'Menu Text', 'manage_options', 'my-slug', 'my_render_func', 'dashicons-admin-generic', 30 );
});
// 2. Settings Initialization (admin_init)
add_action( 'admin_init', function() {
register_setting( 'my_group', 'my_option', array( 'sanitize_callback' => 'sanitize_text_field' ) );
add_settings_section( 'my_section', 'Section Title', '__return_false', 'my-slug' );
add_settings_field( 'my_field', 'Field Label', 'my_field_render', 'my-slug', 'my_section' );
});
// 3. Field Render Callback
function my_field_render() {
$val = get_option( 'my_option', '' );
echo '<input type="text" name="my_option" value="' . esc_attr( $val ) . '" class="regular-text">';
}
// 4. Page Render Callback
function my_render_func() {
if ( ! current_user_can( 'manage_options' ) ) return;
echo '<div class="wrap"><h1>' . esc_html( get_admin_page_title() ) . '</h1>';
echo '<form action="options.php" method="post">';
settings_fields( 'my_group' );
do_settings_sections( 'my-slug' );
submit_button();
echo '</form></div>';
}