Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 68 ยท Shortcodes, Options and Admin Pages

Admin Pages, Menus and List Tables

Add admin menu pages and submenus, check capabilities, show notices, handle forms with admin-post.php and understand WP_List_Table in a WordPress plugin.

A plugin that has any settings, data or tools needs a place in the WordPress dashboard. You add that place with an admin page: a menu entry in the left sidebar that opens a screen your code prints. Around that page sit a few standard pieces: capability checks that decide who may see it, notices that report results, handlers that process form submissions, and WP_List_Table, the class behind the Posts and Users tables.

This lesson shows how to add menu pages, protect them, give feedback and process actions. As the code touches the dashboard, the real WordPress examples are read-only. Two runnable stand-ins at the end model the menu registry and a list table so you can see the logic. We assume you know hooks from Actions and Filters; the settings form that often lives inside these pages is described in The Settings API.

Adding a menu page

Menu items are added on the admin_menu hook:

PHP
add_action( 'admin_menu', 'nw_register_menu' );

function nw_register_menu() {
	add_menu_page(
		'Northwind Tools',          // page title (browser tab and heading)
		'Northwind',                // menu label in the sidebar
		'manage_options',           // capability required
		'nw-tools',                 // menu slug (used in the URL)
		'nw_render_tools_page',     // callback that prints the page
		'dashicons-admin-tools',    // icon
		58                          // position in the menu
	);

	add_submenu_page(
		'nw-tools',                 // parent slug
		'Northwind Reports',
		'Reports',
		'edit_posts',
		'nw-reports',
		'nw_render_reports_page'
	);
}

add_menu_page() creates a top-level entry; add_submenu_page() adds a child under any existing parent slug. Pass the parent's slug as the first argument. When you add a submenu under your own top-level page, WordPress repeats the top-level label as the first submenu item, so the parent page appears in both places.

Shortcuts exist for core menus: add_options_page() puts your page under Settings, add_management_page() under Tools, and add_submenu_page( 'edit.php?post_type=event', ... ) under a custom post type's menu (see Custom Post Types). Under Settings is the right home for a plugin's single settings screen: users already look there.

The page URL is wp-admin/admin.php?page=nw-tools, built from the slug. Slugs must be unique across the whole dashboard, so prefix them.

flowchart TD
    A["Request: admin.php?page=nw-tools"] --> B{"Page registered<br/>on admin_menu?"}
    B -->|"no"| X["Cannot access this page"]
    B -->|"yes"| C{"current_user_can(<br/>menu capability)?"}
    C -->|"no"| X
    C -->|"yes"| D["Run your callback<br/>and print the page"]

A menu page is reachable only if it is registered and the current user holds the capability you passed.

Capabilities protect the page

The capability argument does two jobs. It hides the menu item from users who lack it, and WordPress refuses to open the page URL for them. Pick the least powerful capability that fits: manage_options for site-wide settings (administrators), edit_posts for anything contributors may do, or a custom capability you add to a role. Roles and capabilities get a full lesson in Users, Roles and Capabilities.

Hiding a menu entry is not security on its own. Anything your page does, such as deleting rows or saving values, must check the capability again when it runs, because someone can send a request directly without clicking through the menu:

PHP
function nw_render_tools_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have permission to view this page.', 'northwind' ) );
	}
	?>
	<div class="wrap">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
		<p>Tools go here.</p>
	</div>
	<?php
}

Wrap your output in <div class="wrap"> and start with an <h1>: that is the markup core styles expect. Admin notices are placed right after the first heading inside .wrap.

The first stand-in: a menu filtered by capability

This TryIt models the registry that add_menu_page() and add_submenu_page() fill, and the filtering that decides what each role sees. The roles and capabilities here are a small made-up table (real roles are covered in a later lesson), and the code is plain PHP, not WordPress.

PHP A menu registry filtered by capability

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that this stand-in shows the editor no "Northwind" entry at all, even though one of its children needs only edit_posts, because the parent's own capability is not met. Real WordPress has extra rules for this case, so do not depend on them: register a top-level page with a capability that everyone who needs its children also holds.

Admin notices

A notice is the colored banner at the top of an admin screen. You print it by hooking admin_notices:

PHP
add_action( 'admin_notices', function () {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	if ( isset( $_GET['nw_done'] ) ) {
		echo '<div class="notice notice-success is-dismissible"><p>';
		echo esc_html__( 'Import finished.', 'northwind' );
		echo '</p></div>';
	}
} );

The classes notice-success, notice-error, notice-warning and notice-info pick the color, and is-dismissible adds a close button. Notices appear on every admin screen, so limit yours to the screens that need them (check get_current_screen()->id) or users will resent your plugin. For results after saving a form, the usual trick is to redirect back with a query argument and read it in the notice callback.

Handling form actions with admin-post.php

A settings form can use the Settings API, but a button like "Run import" or "Delete all logs" is an action, not an option. For those, post to wp-admin/admin-post.php and let WordPress dispatch to your hook:

PHP
// In the page: a form that posts to admin-post.php
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
	<input type="hidden" name="action" value="nw_run_import">
	<?php wp_nonce_field( 'nw_run_import' ); ?>
	<?php submit_button( 'Run import' ); ?>
</form>

// The handler: runs for logged-in users
add_action( 'admin_post_nw_run_import', 'nw_handle_import' );

function nw_handle_import() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( 'Not allowed', 403 );
	}
	check_admin_referer( 'nw_run_import' );

	// ... do the work ...

	wp_safe_redirect( add_query_arg( 'nw_done', 1, admin_url( 'admin.php?page=nw-tools' ) ) );
	exit;
}

The hidden action field selects the hook: admin_post_{action} for logged-in users and admin_post_nopriv_{action} for visitors who are not logged in. The handler then does the three checks you will repeat in every privileged action: capability, nonce (check_admin_referer() for admin forms) and, after the work, a redirect with exit so a page refresh does not repeat the action. Nonces are explained in Forms and Nonces.

sequenceDiagram
    participant B as Browser
    participant A as admin-post.php
    participant H as admin_post_nw_run_import
    B->>A: POST action=nw_run_import and nonce
    A->>H: do_action for that action
    H->>H: Check capability and nonce
    H->>H: Do the work
    H-->>B: wp_safe_redirect, then exit

The hidden action field decides which handler runs; the handler must check permission and nonce itself.

Tables of data: WP_List_Table

When your page shows many rows (orders, logs, subscribers), you want sortable columns, pagination, bulk actions and search, the same table that the Posts screen uses. WP_List_Table provides it. You extend the class and implement a few methods:

PHP
if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

class NW_Logs_Table extends WP_List_Table {

	public function get_columns() {
		return array(
			'cb'      => '<input type="checkbox">',
			'message' => 'Message',
			'level'   => 'Level',
		);
	}

	protected function get_sortable_columns() {
		return array( 'level' => array( 'level', false ) );
	}

	protected function column_default( $item, $column_name ) {
		return esc_html( $item[ $column_name ] );
	}

	public function prepare_items() {
		$per_page = 20;
		$current  = $this->get_pagenum();
		$total    = nw_count_logs();

		$this->_column_headers = array( $this->get_columns(), array(), $this->get_sortable_columns() );
		$this->items           = nw_get_logs( $per_page, ( $current - 1 ) * $per_page );

		$this->set_pagination_args( array(
			'total_items' => $total,
			'per_page'    => $per_page,
		) );
	}
}

Then in your page callback you create the object, call prepare_items() and print it with display(). The class does the markup, the pagination links and the sort arrows; you supply the columns and the rows for the current page. Query only the rows you show (a LIMIT and OFFSET) and count the total separately.

One honest caveat: WP_List_Table is an internal class that core does not promise to keep stable. It is widely used and rarely changes in breaking ways, but test after major updates. The block-based admin screens in newer WordPress parts use JavaScript data views instead; for plugin pages, WP_List_Table is still the dependable choice.

Related screen-level features: Screen Options (the tab at the top where users choose rows per page) are added with add_screen_option() in a load-{page} hook, and the per-user value is read with get_user_meta(). Help tabs come from get_current_screen()->add_help_tab().

The second stand-in: how a list table paginates and sorts

The TryIt below does not render real markup. It shows the data logic a list table needs: sort by a column, slice the current page, compute the total page count and print the "Displaying N items" caption.

PHP Sorting and paginating table rows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The important habit is the allow-list for orderby: the column name arrives from a URL, so only accept names you know. The same rule applies to the page number, which is clamped to a valid range.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. On which hook do you call add_menu_page()?

    Menu pages are registered on admin_menu, which fires while the dashboard menu is being built.
  2. 2. A menu page has the capability manage_options. Is checking the capability again inside the callback or form handler still needed?

    The menu capability controls the page screen. A handler that runs on admin-post.php or admin-ajax.php must verify capability itself.
  3. 3. A form has a hidden field action=nw_run_import and posts to admin-post.php. Which hook runs for a logged-in user?

    admin-post.php fires admin_post_{action} for logged-in users and admin_post_nopriv_{action} for visitors.
  4. 4. Why should a list table check the orderby value against a list of known columns?

    orderby arrives in the query string. Accepting only known column names prevents injection and odd behavior.

Summary

  • Register menu pages on admin_menu with add_menu_page() and add_submenu_page(); slugs must be unique and prefixed.
  • The capability argument hides the menu item and blocks the page, but every action must check capability again.
  • Notices go through admin_notices with classes such as notice-success and is-dismissible.
  • Buttons that perform actions post to admin-post.php; the hidden action selects admin_post_{action}, and the handler checks capability and nonce, then redirects and exits.
  • WP_List_Table gives you sortable, paginated tables: implement get_columns(), prepare_items() and set_pagination_args(), and allow-list orderby.
  • WP_List_Table is an internal class: test it after major updates.

Next, move from the dashboard to the data layer: The REST API.